-
-
Save pmgupte/8037523 to your computer and use it in GitHub Desktop.
| <?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" | |
| ?> |
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
foo equals true. And foo equals zero. So, according to rule of transitive relation, true equals zero?!