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?

1

6 Answers 6

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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)   

Comments

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.

Comments

1

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

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.