Saturnix
Saturnix

Reputation: 10564

if statement not being respected in PHP

if ($fromcat == "true" || $fromcat == 1){

    error_log("binding to CAT " . $cat . " because pfc was " . $fromcat);   

} else {

    error_log("binding to ROOM " . $room . " because pfc was " . $fromcat); 

}

please have a look at the code above.

I think everybody agree that if $fromcat is 0 there's no way I could get a "binding to CAT (...)" message in my console.

And yet, here it is:

[01-Apr-2013 22:34:50] binding to CAT single because pfc was 0

How is that even possible? You can't display the word CAT and the number 0 at the same time! Is PHP drunk?

Upvotes: 0

Views: 70

Answers (2)

jmat
jmat

Reputation: 320

It's also a good idea to reverse the order of your condition.

So

if ($fromcat === "true" || $fromcat === 1)

becomes

if ('true' === $fromcat || 1 === $fromcat)

Reason: PHP - reversed order in if statement

Upvotes: 1

Kermit
Kermit

Reputation: 34055

Use the identical (===) comparison operator.

if ($fromcat === "true" || $fromcat === 1) {

    error_log("binding to CAT " . $cat . " because pfc was " . $fromcat);   

} else {

    error_log("binding to ROOM " . $room . " because pfc was " . $fromcat); 

}

You are attempting to compare $fromcat to the string "true". If you wanted to compare it to the boolean true, you would use $fromcat == true. Otherwise:

If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.

Documentation

Upvotes: 3

Related Questions