Skip to content

Instantly share code, notes, and snippets.

@jamiel jamiel/gist:1950093
Created Mar 1, 2012

What would you like to do?
Why does count(false) == 1 in PHP?
Why does count(false) == 1 in PHP?
If you have ever been caught out by doing if (count($var)) and wondered why this
passes when a previous assignment failed and set this to false, the reason is
actually quite simple. count() was designed to be used with arrays, and so values
are always cast to an array internally before checking the number of elements. If
you cast a boolean to an array it will be come an array with one element set to the
value of the boolean. See:
jamiel@gentoo ~ $ php -a
Interactive shell
php > var_dump((array) false);
array(1) {
Note, NULL cannot be cast to an array so count(null) will still equal 0.
php > var_dump((array) null);
array(0) {
You shouldn't use count() as a comparison for an if statement unless you are sure you are dealing with an array.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.