Spencer
Spencer

Reputation: 22418

PHP if condition with strings

I am trying to write would be a simple if condition.

function genderMatch($consumerid1, $consumerid2)
    {
    $gender1=getGender($consumerid1);
    $gender2=getGender($consumerid2);
    echo $gender1;
    echo $gender2;
    if($gender1=$gender2)   
      echo 1;
      return 1;
    else
       echo 0;
       return 0;
}

The output of the getGender function is either a M or F. However, no matter what I do gender1 and gender2 are returned as the same. For example I get this output: MF1

I am currently at a loss, any suggestions?

Upvotes: 1

Views: 12508

Answers (6)

mqchen
mqchen

Reputation: 4193

You are using a single = which sets the variable, ie. the value of $gender1 is set to be the value of $gender2.

Use the === operator instead: if($gender1 === $gender2). It is usually a good idea to do strict comparisons rather than loose comparisons.

Read more about operators here: php.net

Another alternative is to use strcmp($gender1, $gender2) == 0. Using a comparer method/function is more common in languages where the string-datatype isn´t treated as a primary data-type, eg. C, Java, C#.

Upvotes: 0

Kyle
Kyle

Reputation: 22278

You have some structural problems with your code as well as an assignment instead of a comparison.

Your code should look like this:

function genderMatch($consumerid1, $consumerid2){
    $gender1=getGender($consumerid1);
    $gender2=getGender($consumerid2);
    echo $gender1;
    echo $gender2;
    if($gender1==$gender2){ 
      echo 1;
      return 1;
    }else{
       echo 0;
       return 0;
    }
}

Notice the double '=' signs in the if statement. This is a comparison. A single '=' is an assignment. Also, if you want to execute more than 1 line of code with an if/else, you need brackets.

Upvotes: 1

cypher
cypher

Reputation: 6992

Your using the assignment operator = instead of comparsion operators == (equal) or === (identical).
Have a look at PHP operators.

Upvotes: 1

circusdei
circusdei

Reputation: 1967

this:

if($gender1=$gender2)   

should be

if($gender1==$gender2)   

notice the extra ='s sign. I think you might also need curly brackets for multiple lines of an if/else statement.

Upvotes: 1

mpj
mpj

Reputation: 5367

You have to put two == for comparison. With only one, as you have right now, you are assigning the value to the first variable.

     if($gender1=$gender2)   

would become

   if($gender1==$gender2)   

Upvotes: 3

phihag
phihag

Reputation: 288298

if ($gender1 = $gender2)

assigns the value of $gender2 to $gender1 and proceeds if the result (i.e. the value of $gender2) evaluates to true (every non-empty string does). You want

if ($gender1 == $gender2)

By the way, the whole function could be written shorter, like this:

function genderMatch($cid1, $cid2) {
  return getGender($cid1) == getGender($cid2);
}

Upvotes: 7

Related Questions