For casting directly to a boolean this is how it works.
- All string with a length > 0 are true
- All non 0 numbers are true
- All non-empty arrays are true
- All objects are true
Then these rules for comparing variables of the same type:
- Objects are equivalent if their properties are equal
- Arrays are equivalent if their keys and elements are equal
- Strings are equivalent if they would produce the same output
- Numbers are equivalent if they are mathematically equivalent
- Booleans are equivalent if they have the same value.
For variable of different types the type that is higher on the above list is cast to the one that is lower then the comparison is made.
===
and !==
operators don't cast prior to comparing but you should note objects are only ===
if they are the same instance.
The really odd one is arrays, they are ===
if they have the same keys and values defined in the same order.
$a = array("a"=>1, "b"=>2);
$b = array("b"=>2, "a"=>1);
$a == $b; // true
$a === $b; // false
and empty()
is equivalent to !(bool)$var
EXCEPTIONS
- Casting an array to a string will trigger a notice and unhelpfully cast as the text
Array
- Casting an object without a
__toString
method to a string will get you a fatal error. - Objects will not implicitly cast to an array, so any time you compare an object to an array it will yield a false (UPDATE confirmed that this is true even if object implemtents the
ArrayAccess
interface)