1

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?

Spencer
  • 21,348
  • 34
  • 85
  • 121

6 Answers6

7
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);
}
phihag
  • 278,196
  • 72
  • 453
  • 469
3

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)   
Manuel Pedrera
  • 5,347
  • 2
  • 30
  • 47
1

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.

circusdei
  • 1,967
  • 12
  • 28
1

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

cypher
  • 6,822
  • 4
  • 31
  • 48
1

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.

Kyle
  • 21,978
  • 2
  • 60
  • 61
0

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#.

mqchen
  • 4,195
  • 1
  • 22
  • 21