CKTIS / PHP
count: element count, not the last index
count returns the number of array elements or the result of a Countable object method. It does not measure strings or assume consecutive indexes starting at zero.
Version: PHP 8.4
Syntax
count(Countable|array $value, int $mode = COUNT_NORMAL): intThe array [2 => "a", 8 => "b"] has two elements, so count gives 2 rather than 9. An empty array has 0 elements. Replacing a value under an existing key does not add an element.
The default COUNT_NORMAL counts only the top array level. COUNT_RECURSIVE adds elements of nested arrays and also counts the positions containing those arrays. It therefore does not count just terminal values. Cyclic references produce a warning.
In PHP 8.4, count(null) and an ordinary string argument raise TypeError. An object must implement Countable; being iterable alone is insufficient. For uncertain input, check is_countable and separately decide what missing data means.
The example compares normal and recursive counting and catches a type error. Do not automatically replace every invalid input with an empty array: that could hide a data retrieval failure rather than represent a genuinely empty collection.
Examples
<?php
declare(strict_types=1);
echo count([2 => "a", 8 => "b"]), "\n";
$groups = [[1, 2], []];
echo count($groups), " ", count($groups, COUNT_RECURSIVE), "\n";
try {
count(null);
} catch (TypeError $error) {
echo "TypeError\n";
}
Result
2 2 4 TypeError