Reputation: 2743
Do you know why <?= count(false) ?>
returns 1
?
Upvotes: 19
Views: 10758
Reputation: 31
A nice way to remember this in your mind:
Upvotes: 3
Reputation: 464
It looks to me like PHP is preventing one from using count()
to determine if an element is an array or an object. They have dedicated functions for this (is_array()
, is_object()
) and it may be tempting to naively use count()
and check for a false
condition to determine array or object. Instead, PHP makes non-objects, non-arrays return 1
(which is truthy) so that this method cannot be be naively used in this way (since 0
is a valid, falsy result for an empty array/object).
This may be the why behind the choice of value to be returned by the function in the situation you're describing.
Upvotes: 2
Reputation: 29658
It's specified behavior:
If var is not an array or an object with implemented Countable interface, 1 will be returned.
According to http://php.net/manual/en/function.count.php
Upvotes: 27
Reputation: 79031
Because false
is also a value and if the count() does not get array but a valid variable it returns true
which is 1
.
$result = count(null);
// $result == 0
$result = count(false);
// $result == 1
Upvotes: 10