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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

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

Parameters

ParameterDescription
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

Count elementsTry it yourself
<?php
$fruits = ["apple", "banana", "cherry"];
echo count($fruits), "\n";
echo count([]), "\n";

Output

3
0
Nested arraysTry it yourself
<?php
$menu = ["drinks" => ["tea", "coffee"], "food" => ["cake"]];
echo count($menu), "\n";
echo count($menu, COUNT_RECURSIVE), "\n"; // 2 groups + 3 items

Output

2
5
Not for stringsTry it yourself
<?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

VersionChange
PHP 4.0Added
PHP 8.0Throws a TypeError for values that aren't arrays or Countable; before, it warned and returned 1.

In other languages

Was this page helpful?