Why does count (false) return 1?

Do you know why <?= count(false) ?> Returns 1 ?

+14
php count
Mar 10 '13 at 20:57
source share
4 answers

Specified behavior:

If var is not an array or an object with an implemented counter, an interface will be returned.

According to http://php.net/manual/en/function.count.php

+22
Mar 10 '13 at 20:59
source share
— -

Because false also a value, and if count () does not receive an array, but a real variable, it returns true , which is 1 .

 $result = count(null); // $result == 0 $result = count(false); // $result == 1 
+8
Mar 10 '13 at 20:59
source share

It seems to me that PHP does not allow the use of count() to determine if an element is an array or an object. They have special functions for this ( is_array() , is_object() ), and it may be tempting to use count() naively and check the false condition to define an array or object. Instead, PHP does non-objects, non-arrays returns 1 (which is true), so this method cannot be naively used that way (since 0 is a valid, false result for an empty array / object).

This may be the reason for choosing the value returned by the function in the described situation.

+1
Dec 28 '13 at 20:19
source share

A good way to remember this in your mind:

  • count (false) is basically the same as:
  • count ("one boolean"), and therefore the result is "ONE".
+1
Apr 6 '16 at 8:40
source share



All Articles