I'm a curious programmer. So these days I was reading the documentation from the PHP site and this link was "PHP type comparisons" http://www.php.net/manual/en/types.comparisons.php
I decided to do some exercises to fill the tables of comparisons but there are some answers that I can not see why, for example:
<?php
var_dump(false == array()); // Okay, an empty array is considered false. True result
var_dump('' == array()); // false ? Why not true if an empty string is considered false ?
var_dump(0 == array()); // false ? Why ?
var_dump(null == array()); // true. Why ?
?>
Can you help me about this? I can not understand why some comparisons, I can not find anywhere explanation.
Here is the reason why.
Case one will cast the array() to a boolean, resulting in false.
Case two and three are explained here, the scalars are cast to arrays:
For any of the types: integer, float, string, boolean and resource, converting a value to an array results in an array with a single element with index zero and the value of the scalar which was converted. In other words, (array)$scalarValue is exactly the same as array($scalarValue).
Case four is explained here:
Converting NULL to an array results in an empty array.
It's all about type juggling, which type wins over the other type.
For instance, when you compare an number with a string, the number always wins so the string will be converted into a number. So "12abc" == 12 is true in PHP.
false) with something, that something is converted to a boolean. (bool) array() is false, so false == false is true.array([0] => VALUE_OF_OTHER) (in other words, converted to an array). That means that the comparisation becomes array('') == array(), which is falsearray(0) == array() is falsearray(null) means just an array with nothing, thus array(null) == array() (which is the comparisation you did), so the result is true.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With