count()

count() — Counts all elements in an array or in a Countable object.

Built-in function of PHP 8.5. The manual lists it as available in PHP 4, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

Counts all elements in an array when used with an array. When used with an object that implements the Countable interface, it returns the return value of the method Countable::count().

Signature

count(Countable|array $value, int $mode = COUNT_NORMAL): int

Parameters

ParameterTypeWhat it takes
$valueCountable|arrayAn array or Countable object.
$modeintIf the optional mode parameter is set to COUNT_RECURSIVE (or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array.

Return value

Returns the number of elements in value. Prior to PHP 8.0.0, if the parameter was neither an array nor an object that implements the Countable interface, 1 would be returned, unless value was null, in which case 0 would be returned.

Example

A runnable snippet:

$a[0] = 1; $a[1] = 3; $a[2] = 5; var_dump(count($a)); $b[0] = 7; $b[5] = 9; $b[10] = 11; var_dump(count($b));

Output:

int(3) int(3)

Changelog

VersionChange
8.0.0Now throws a ValueError if mode is not COUNT_NORMAL or COUNT_RECURSIVE.
8.0.0count() will now throw TypeError on invalid countable types passed to the value parameter.
7.2.0count() will now yield a warning on invalid countable types passed to the value parameter.

See also

is_array(), strlen(), is_countable()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page count() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.