Skip to content
Tutorials Center
My learning

Topics

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
<?php
echo count([10, 20, 30]);                 // 3
echo count(["a" => 1, "b" => 2]);         // 2

Try it

PHP Counting arrays and nested arrays

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.

PHP Countable objects and non-countable values

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

PHP
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_RECURSIVE counts 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, use array_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 than count($items) === 0.
  • Null elements count. count([null]) is 1. Use count(array_filter($a)) to count truthy values, or array_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 with COUNT_RECURSIVE.
  • Counting characters or values: use strlen() for strings, substr_count() for substrings and array_count_values() for frequencies.
  • Loops. for ($i = 0, $n = count($a); $i < $n; $i++) avoids repeating the call, though the saving is tiny.