Jump to content

[SOLVED] Arbitrary If statement behavior?


daneyuleb

Recommended Posts

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

Link to comment
https://forums.phpfreaks.com/topic/156860-solved-arbitrary-if-statement-behavior/
Share on other sites

$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?

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!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.