count

Counts the elements in an array or a Countable object, optionally descending into nested arrays.

Signature
count(Countable|array $value, int $mode = COUNT_NORMAL): int
  • Added in PHP 4.0

Parameters

ParameterTypeDescription
$valueCountable|arrayThe array or Countable object to count.
$modeoptionalint= COUNT_NORMALCOUNT_NORMAL counts only the top level; COUNT_RECURSIVE (or 1) also counts elements inside nested arrays.

Return value

intThe number of elements in the array, or the result of the object's count() method for a Countable. With COUNT_RECURSIVE, nested arrays are counted as well as their contents.

Errors

Throws TypeError when passed a value that is neither an array nor a Countable object. Emits E_WARNING if recursion is detected while counting with COUNT_RECURSIVE.

Changelog

  • PHP 8.0.0count() now throws a TypeError for values that are neither array nor Countable. Previously it emitted a warning and returned 1 (or 0 for null).
  • PHP 7.2.0count() emits a warning for invalid countable types passed to the value parameter.

count returns how many elements an array holds. Given an object that implements Countable, it calls that object's count() method instead — which is how ArrayObject, SplFixedArray and most collection classes report their size.

When to reach for it

Any time you need the size of an array: pagination totals, guarding against an empty result set, or deciding between singular and plural wording. For "is it empty?" prefer $array === [] or empty($array) — they express the intent directly and never have to count.

What trips people up

Since PHP 8.0 passing a non-countable value is a fatal TypeError, not a warning returning 1. Code that used to do count($maybeNull) now crashes, so check with is_countable or use the null coalescing operator: count($rows ?? []).

COUNT_RECURSIVE is more surprising than it looks — it counts the nested arrays themselves as well as their contents. [[1,2],[3]] counts as 5, not 3: two sub-arrays plus three integers.

Finally, count is O(1) on arrays because PHP stores the element count, so calling it inside a loop condition is cheap. That is not true for a Countable object, whose count() method may do real work.

sizeof is an alias with identical behaviour.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Show "12 results found" above a search listing.
  • Guard a report so it skips the render step when the row set is empty.
  • Compute the total number of leaf values in a nested structure with COUNT_RECURSIVE.

Frequently asked questions

What is the difference between count and sizeof?

There is none — sizeof is an alias of count with identical behaviour. count is the preferred spelling because sizeof suggests a byte size to programmers coming from C.

How do I get the length of a string in PHP?

Use strlen for bytes or mb_strlen for characters. count only works on arrays and Countable objects and throws a TypeError on a string.

Why does count return more than I expect on a nested array?

You are probably passing COUNT_RECURSIVE, which counts each nested array as an element in addition to counting its contents. Use the default COUNT_NORMAL for the top-level size.

More examples

Non-countable values now throw

On PHP 8 the first count() throws instead of returning 1 as PHP 7.1 and earlier did, so the catch block runs. The null coalescing fallback prints 0, and is_countable confirms why the direct call failed.

Example · php
<?php
$rows = null;

try {
    echo count($rows), "\n";
} catch (TypeError $e) {
    echo "TypeError caught\n";
}

echo count($rows ?? []), "\n";   // 0 — the safe form
var_dump(is_countable($rows));   // bool(false)

Counting only the leaves

COUNT_RECURSIVE reports 8 because it adds the three container arrays to the five integers. When you want only the scalar values, array_walk_recursive with a counter gives the honest answer of 5.

Example · php
<?php
$tree = ['a' => [1, 2], 'b' => [3, [4, 5]]];

$all = count($tree, COUNT_RECURSIVE);
$leaves = 0;
array_walk_recursive($tree, function () use (&$leaves) { $leaves++; });

echo "recursive: $all\n";  // 8 — includes the 3 nested arrays
echo "leaves: $leaves\n";  // 5 — the actual values

count is cheap in a loop condition

PHP stores an array's element count in its header, so count() is a constant-time lookup and needs no caching in a variable before the loop. Each iteration shifts one element off and the loop exits when the array is empty.

Example · php
<?php
$queue = ['a', 'b', 'c'];

while (count($queue) > 0) {
    echo array_shift($queue), "\n";
}

echo count($queue), "\n"; // 0

Discussion

  • Be the first to comment on this lesson.