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

Link to comment
Share on other sites

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!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.