Falsy values are values that are considered equivalent to false
in PHP when evaluated in a boolean context. According to the official PHP docs, the following values are considered to be falsy:
- Boolean
false
; - Integer
0
; - Float
0.0
and-0.0
; - Empty String;
- String
"0"
; - Array with no elements,
[]
; NULL
type;- Some internal objects, like
SimpleXML
objects created from empty elements (i.e. elements that have no children and attributes), may behave as falsy when explicitly converted to boolean.
These values evaluate to a boolean false
when:
- They're explicitly converted to a boolean (for example by casting);
- An operator, function or control structure requires a boolean argument (in which case the value is converted to a boolean implicitly/automatically).
For example:
echo var_dump((bool) false); // false
echo var_dump((bool) 0); // false
echo var_dump((bool) 0.0); // false
echo var_dump((bool) ''); // false
echo var_dump((bool) '0'); // false
echo var_dump((bool) []); // false
echo var_dump((bool) null); // false
echo var_dump((bool) new SimpleXMLElement('<foo />')); // false
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.