简体   繁体   中英

if statement condition is triggering regardless of wether or not condition is met

This if statement triggers regardless of the values in the condition , i substituted number for explanation sake. Why is the condition triggering the execution regardless if the condition is true or not. Ive tried every scenario but the execution in the statement triggers every time .

if(1 != 1 && 1 != 2 ){
execute code
exit();
 }

here is the exact code:

if($name1 != $winner && $name2 != $winner ){
echo " The player you chose as winner is not associated with match id: $match_id ";
exit();
}

It is not possible for the condition mentioned in the post to return true .

However what you are saying may happen if you write code something like below:

if(1 != 1 && 1 != 2 );{
    echo 'case 1';
}

Note the ; after the if(). Are you sure your code does not have the semi-colon after the if()? If you have mistakenly placed a ; then the if statement is evaluated as a single line statement and the code within the if-block is considered by the interpreter as outside of the if condition.

Edit based on the updated question

Please check the following:

  1. $winner is correctly set to either of $name1 or $name2 .
  2. Verify that variable declaration scope for $winner is correct - it has been some time since I have done PHP but this is possibly something else to look out for.

Other than these I do not see any other reason why this code should behave the way you state.

Just maybe ... Have a very close look at the values of the four variables involved.

Comparisons using != can give some surprising results.

See here and here . EDIT: Links fixed

Even if that doesn't solve this problem, better to try to use !== wherever possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM