daneyuleb Posted May 4, 2009 Share Posted May 4, 2009 I'm a PHP newbie--can someone tell me if my interpreter is buggy, or do the below 4 IF statements really the expected, seemingly arbitrary, behavior? 1 and 2 both treat the statement as true even though x has different values. If it is expected--are IF statements supposed to always include double-quotes to avoid it evaluating the variable as a Boolean if its value is 0 or 1? Don't think I've ever read that... $y="hello"; $x=0; if ($x==$y) { print "$y == $x"; } >> hello == 0 <------WTF! $x='hello'; if ($x==$y) { print "$y == $x"; } >> hello == hello $x=0; if ("$x"==$y) { print "$y == $x"; } >> $x='1'; if ($x==$y) { print "$y == $x"; } >> Thanks! -Daniel Quote Link to comment Share on other sites More sharing options...
Ken2k7 Posted May 4, 2009 Share Posted May 4, 2009 $y="hello"; $x=0; if ($x==$y) { print "$y == $x"; } >> hello == 0 <------WTF! $x='hello'; if ($x==$y) { print "$y == $x"; } >> hello == hello $x=0; if ("$x"==$y) { print "$y == $x"; } >> $x='1'; if ($x==$y) { print "$y == $x"; } >> 1. When comparing a number and a string, the string is treated as 0. As expected. Edit: I forgot to point out that if you want to compare it straight like that, you need 3 equals. 2. Nothing special there. As expected. 3. The string "$x" is not equal to the string "hello". As expected. 4. The string '1' is not equal to "hello". As expected. That help? Quote Link to comment Share on other sites More sharing options...
daneyuleb Posted May 5, 2009 Author Share Posted May 5, 2009 Yep, that helped a lot. I ran into this in a case where my "x" value could have been a number or a string, and the behavior caught me by surprise when 0's gave false positives when compared to a string (as in the first case). Gotta think this catches people fairly often when both values that can be either numbers or strings are being compared...I wish this was talked about more in the intro's on PHP comparisons. Anyway, using "===" is the solution for me. Thanks for the tip! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.