0

I'm fairly new to PHP so forgive me if this function is badly done.

I have a function:

function socialLink($sm_type = NULL) {
   if ($sm_type = 'twitter') {
     echo 'https://www.twitter.com';
   } else {
     echo 'https://www.facebook.com';
   }
}

In my code when I call the function socialLink('facebook'); it echo's the Twitter URL.

Surely it should echo the Facebook URL since $sm_type would be equal to 'facebook' not twitter ?

Any help would be appreciated.

regen
  • 91
  • 1
  • 1
  • 7
  • your test is a classic error : should be $sm_type == 'twitter'. As written, you assigne a value to $sm_type, always true. – YvesLeBorg Jul 21 '17 at 11:31
  • Make sure that you read proper documentation about the Comparison Operators (in any programming language): http://php.net/manual/en/language.operators.comparison.php – Nikhil Jul 21 '17 at 11:32
  • Thank you for the link. I could definitely do with revising more of the PHP Manual. – regen Jul 21 '17 at 11:36
  • Possible duplicate of [The 3 different equals](https://stackoverflow.com/questions/2063480/the-3-different-equals) – Qirel Jul 21 '17 at 11:52

4 Answers4

5

Set your if condition with this,

function socialLink($sm_type = NULL) {
   if ($sm_type == 'twitter') {
     echo 'https://www.twitter.com';
   } else {
     echo 'https://www.facebook.com';
   }
}

See this.

Virb
  • 1,639
  • 1
  • 16
  • 25
  • It was something so simple all along. Can't believe I couldn't see that. Thank you. – regen Jul 21 '17 at 11:36
  • 3
    Happy to help dude. Be careful for small mistakes. Please accept the answer if you got your output.. Cheerss..!! – Virb Jul 21 '17 at 11:39
3
function socialLink($sm_type = NULL) {

   if ($sm_type == 'twitter') {
     echo 'https://www.twitter.com';
   } else {
     echo 'https://www.facebook.com';
   }
}

NOTE: Single = use to assign the value and = = use to compare values

Different's Between = , = = , = = =

  • = operator Used to just assign the value.
  • = = operator Used to just compares the values not datatype
  • = = = operator Used to Compare the values as well as datatype.
RïshïKêsh Kümar
  • 4,734
  • 1
  • 24
  • 36
2

Your if statement does not use a comparison operator, it is an assignment (=). For a comparison, please use "==".

if ($sm_type == 'twitter') {
     echo 'https://www.twitter.com';
} else {
    echo 'https://www.facebook.com';
}
BenRoob
  • 1,662
  • 5
  • 22
  • 24
2
if ($sm_type == 'twitter') {
 echo 'https://www.twitter.com';
} else {
echo 'https://www.facebook.com';
}

In php == is use for string comparison so, In this case you can't used = for that, simple :)

Puja
  • 451
  • 2
  • 5
  • 20