is_countable()
The count()
function can be used to either count the
elements of an array or “something inside an object”. The latter
means that the count()
function delegates the actual
counting operation a method when used on an object. This object
needs to implement the Countable
interface for this to
work:
$array = [1, 2, 3];
var_dump(count($array));
$object = new stdClass;
var_dump(count($object));
class C implements Countable
{
public function count(): int
{
return 0;
}
}
$object = new C;
var_dump(count($object));
Using count()
on an object that does not implement
the Countable
interface returns 1
and
triggers a warning. Executing the code shown above will print the
output shown below:
int(3)
PHP Warning: count(): Parameter must be an array or an object
that implements Countable in ...
int(1)
int(0)
In previous versions of PHP is_array()
and
instanceof
had to be used to determine whether a
variable can be passed to count()
without triggering
that warning:
if (is_array($variable) || $variable instanceof Countable) {
// count($variable) can be used
}
Thanks to the new is_countable()
function, the code
shown above can now be replaced with
if (is_countable($variable)) {
// count($variable) can be used
}