PHP 8 reference · Array Functions
PHP count() Function
Return the number of elements in an array or Countable object. With COUNT_RECURSIVE it also counts nested elements.
PHP 8 Since 4.0
Syntax
count(Countable|array $value, int $mode = COUNT_NORMAL): int
Parameters
| Parameter | Description |
|---|---|
value |
An array or a Countable object. |
mode optional |
COUNT_RECURSIVE also counts the elements of nested arrays. Default: COUNT_NORMAL |
Return value
The number of elements.
Examples
<?php
$fruits = ["apple", "banana", "cherry"];
echo count($fruits), "\n";
echo count([]), "\n";
Output
3 0
<?php
$menu = ["drinks" => ["tea", "coffee"], "food" => ["cake"]];
echo count($menu), "\n";
echo count($menu, COUNT_RECURSIVE), "\n"; // 2 groups + 3 items
Output
2 5
<?php
try {
count("hello");
} catch (TypeError $e) {
echo "TypeError: use strlen() for strings\n";
}
Output
TypeError: use strlen() for strings
sizeof() is an alias of count(). Calling count() in a loop condition is cheap: PHP stores an array's size.
Version history
In other languages
len()· Pythonarray.length· JavaScript
Related
strlen()· Return the length of a string in bytes. Multibyte characters such as é count as several bytes; use mb_strlen() to count characters.array_count_values()· Count how many times each value occurs in an array, returning value => count pairs.array_key_last()· Return the last key of an array without moving its internal pointer, or null for an empty array. Added in 7.3.- PHP Arrays · tutorial
- PHP Array Functions · tutorial