PHP Reference ยท Array Functions
PHP count() function
Reference for PHP count() and sizeof(): count array elements or Countable objects, COUNT_RECURSIVE, the TypeError for non-countable values and empty checks.
count() returns the number of elements in an array, or the result of the count() method of an object that implements the Countable interface. For an array it is a constant-time operation, because PHP stores the size with the array, so it is fine to call in a loop condition.
sizeof() is an alias with exactly the same behavior. Most style guides prefer count(), because sizeof() suggests the C operator that returns a size in bytes.
<?php echo count([10, 20, 30]); // 3 echo count(["a" => 1, "b" => 2]); // 2
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
count(Countable|array $value, int $mode = COUNT_NORMAL): int sizeof(Countable|array $value, int $mode = COUNT_NORMAL): int
| Name | Description |
|---|---|
$value |
An array or an object implementing Countable. |
$mode |
COUNT_NORMAL (0, default) counts the top-level elements. COUNT_RECURSIVE (1) also counts the elements of nested arrays. |
Return value: the number of elements as an int.
Errors: since PHP 8.0, passing anything else (null, a string, a number, a plain object) throws a TypeError. Earlier versions returned 1 or 0 with a warning.
Usage notes
COUNT_RECURSIVEcounts the containers too. In[[1, 2], [3]]the result is 5: two inner arrays plus three numbers. It is rarely what you want; to count leaf values, usearray_walk_recursive(). Recursive arrays (an array containing a reference to itself) trigger a warning.- Don't count to test for emptiness in conditions you can write simply.
if (!$items)or$items === []is clearer thancount($items) === 0. - Null elements count.
count([null])is 1. Usecount(array_filter($a))to count truthy values, orarray_sum()with a boolean map for other counts. - Possibly-null variables need a guard in PHP 8:
count($maybe ?? []). - Countable objects decide for themselves what
count()returns, and only the top level, even withCOUNT_RECURSIVE. - Counting characters or values: use
strlen()for strings,substr_count()for substrings andarray_count_values()for frequencies. - Loops.
for ($i = 0, $n = count($a); $i < $n; $i++)avoids repeating the call, though the saving is tiny.
Related
array_count_values(),array_sum(),Countable,empty,isset- Lessons: Arrays, Array functions