Created
March 1, 2012 14:17
-
-
Save jamiel/1950093 to your computer and use it in GitHub Desktop.
Why does count(false) == 1 in PHP?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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