Skip to content

Instantly share code, notes, and snippets.

@jamiel
Created March 1, 2012 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamiel/1950093 to your computer and use it in GitHub Desktop.
Save jamiel/1950093 to your computer and use it in GitHub Desktop.
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) {
[0]=>
bool(false)
}
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