Forum Moderators: coopster

Message Too Old, No Replies

I think this is really strange...

         

benj0323

6:22 am on Nov 24, 2004 (gmt 0)

10+ Year Member



Why in the world is this if statement true?

$i = 0;
$r = 'some random string';

if($i==$r) echo 'This is retarded';

I was under the impression that 0 did not equal "some random string". Is this a bug or something?

uncle_bob

10:08 am on Nov 24, 2004 (gmt 0)

10+ Year Member



In order to compare the two variables, php needs to convert them into the same type, so it changes the string into a number, so it can compare it with the other number. However the numeric value of the string is zero, hence you get 0==0. If you compared the string to any other number it would return false.

The moral of this story, is comparing values of different types can can have unexpected consequences.

PCInk

10:24 am on Nov 24, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



if($i eq $r) echo 'This is retarded';

Will not print. The 'eq' compares strings - thus converting $i to a string: '0' (temporary conversion for the comparison only). This does not equal 'some random string', as you expected when you tried it.

Bonusbana

11:10 am on Nov 24, 2004 (gmt 0)

10+ Year Member



if($i === $r) echo 'This is retarded';
will not produce "This is retarded" either.

coopster

1:14 pm on Nov 24, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



PCInk, that's Perl. 'eq' isn't going to work in PHP.

I've done it too ;)

Comparison Operators [php.net]