Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php operator == (sort of equality) and the integer 0

php, my dearest old frienemy.

ok, so i can come to terms with why the string '0' would be a falsie value. that's only fair seeing as how '0' is the same as 0 in a loosely typed language, and 0 is false in a loosely typed language. so this gives that false == 0 == '0'.

fine fine... BUT!! what is this all about?

<?php
    print "number of surprised persons: " . ('false' == 0);

the output is....

number of surprised persons: 1

how is this reasonable? am i the only one who's surprised by this? what am i failing to see?

further testing has proven that the integer 0 is equal (by operator ==) to

0        <-- integer
false    <-- boolean
null     <-- just.. you know, null
'0'      <-- string
''       <-- string
'false'  <-- string
'true'   <-- string
'null'   <-- string

naturally, i mostly use operator === to compare stuff. and now that i know about this, i'll have to adjust my programming of course, no question about that. but still! can someone shed some light pl0x?

like image 971
davogotland Avatar asked Mar 03 '26 10:03

davogotland


2 Answers

It's because, when you compare a string to an integer, they don't both get converted to strings, or to booleans - they get converted to integers. For PHP, when you think about it, this isn't strange at all (comparatively, I suppose).

'true' == 0
// is the same as
(int)'true' == 0
// is the same as
0 == 0
// is the same as
true

And this is true for any non-numeric string as well as the string "0". The reason 1 is printed out is because the string version of true is 1 (and the string version of false is an empty string).

like image 62
Ry- Avatar answered Mar 04 '26 23:03

Ry-


As far as you're concerned about the output:

('false' == 0) = boolean TRUE = string "1".

echo is triggering string context.

But from your comment below I've just seen, that you'd like to learn more about the comparison. Take a look what you do:

Example     Name     Result
$a == $b    Equal    TRUE if $a is equal to $b after type juggling.

so you are doing a non-strict comparison of a number with a string:

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. (REF)

Note: Number, not integer as written in the accepted answer:

<?php
print "number of surprised persons: " . ('false' == 0.3 - 0.2 - 0.1);

Have fun.

like image 23
hakre Avatar answered Mar 05 '26 00:03

hakre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!