Created
December 19, 2013 10:54
-
-
Save pmgupte/8037523 to your computer and use it in GitHub Desktop.
Another PHP goof-up.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| echo ("foo" == 0)?"foo equals 0\n":"foo does not equal 0\n"; // prints "foo equals 0" | |
| echo ("foo" == true)?"foo equals true\n":"foo does not equal true\n"; // prints "foo equals true" | |
| echo (true == 0)?"true equals 0\n":"true does not equal 0\n"; // prints "true does not equal 0" | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Equality always happens on same data type.
in C/C++: you cannot compare two different data types. First you have to "convert" them to same data type explicitly and compare them. So, you have to do "conversion" explicitly in C.
PHP:
php support weak typing, hence you can compare any data types.
But this does not mean that PHP doing something extraordinary.
The underlying PHP parser/interpreter is written C. you already know the comparison in C.
But here PHP do the "Conversion" for you. and then asks C engine to compare the values.
true/false are "Integers" internally. They are actually represented as 1 and 0 by the Zend C engine.
Strings are always converted to Integers before they are compared to any Numeric values.
all string values evaluated to "0" in comparison.
("foo" == 0): "foo" will be converted to 0 by PHP, so 0 == 0
("foo" == true): 0 is not equal to "true". "true" is nothing but 1. So 0 == 1
(true == 0): same as above , 1 == 0