regen
regen

Reputation: 91

php Function echo's wrong string

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.

Upvotes: 0

Views: 126

Answers (4)

Puja
Puja

Reputation: 461

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 :)

Upvotes: 2

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.

Upvotes: 3

Virb
Virb

Reputation: 1578

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.

Upvotes: 5

BenRoob
BenRoob

Reputation: 1722

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';
}

Upvotes: 2

Related Questions