PHP Advent

#[Language]

PHP Array Length: count(), sizeof(), and Performance

By Rodney Renner ·

A dark wooden craftsman workbench illuminated by a warm brass desk lamp features an antique abacus, precision calipers and depth gauges, and an open notebook with memory block diagrams beside a closed laptop.

Use PHP's built-in count() function to get the number of elements in an array. It returns an integer. PHP also has sizeof(), an exact alias that accepts the same arguments and returns the same result. For a standard flat array, count($array) takes constant time, O(1), because the Zend Engine stores the element count in the array's internal data structure.

PHP arrays are ordered hash tables. Contiguous integer lists, sparse keys, and associative key-value pairs all use the same underlying type, so you do not need a different counting function for each. The choices come when you work with nested arrays or objects that implement Countable. Empty checks and loop conditions also deserve attention, particularly when a variable might contain something other than an array. In PHP 8, an invalid argument to count() throws a TypeError that is fatal if left unhandled.

The PHP count manual and the PHP sizeof manual document the signatures and behavior.

The Fundamentals of count() and sizeof()

The signature is count(Countable|array $value, int $mode = COUNT_NORMAL): int: it accepts an array or a countable object, along with an optional counting mode parameter.

With the default mode, count() counts only the array's top-level elements.

Counting Indexed Arrays

An indexed array uses integers as keys, whether sequential or custom. For a basic list, the count is the number of stored items:

$frameworks = ['Laravel', 'Symfony', 'Laminas'];
$total = count($frameworks);

echo $total; // Outputs: 3

PHP arrays can also have gaps between their numeric keys. They are associative hash tables rather than fixed-size contiguous memory blocks, so count() counts stored entries, not the distance between the lowest and highest index:

$sparse = [
    0 => 'Alpha',
    10 => 'Beta',
    100 => 'Gamma',
];

echo count($sparse); // Outputs: 3

The highest key here is 100, but the array contains exactly three key-value pairs. Other languages might require 101 allocated slots for an index of 100; PHP counts the keys that exist. This matters when you use the length to access an element. An array of length 5 does not necessarily have entries at indices 0, 1, 2, 3, and 4. Assuming that it does can produce undefined index notices with sparse or associative keys.

If an algorithm needs contiguous numeric indices, use array_values($array) to re-index the entries sequentially from 0 to count($array) - 1.

Counting Associative Arrays

Associative arrays use strings as keys. count() treats those keys the same way as numeric indices:

$user = [
    'id' => 4821,
    'username' => 'jdoe',
    'email' => 'jdoe@example.com',
    'status' => 'active',
];

echo count($user); // Outputs: 4

The same rule applies when an array mixes numeric and string keys: each distinct key-value entry contributes one to the count. For a smaller associative example, count(['a' => 1, 'b' => 2]) returns 2.

$mixed = [
    0 => 'First',
    'status' => 'Pending',
    1 => 'Second',
    'code' => 200,
];

echo count($mixed); // Outputs: 4

The sizeof() Alias Explained

In the Zend Engine standard library source, sizeof maps to the same internal function handler as count. Choosing one name over the other changes neither the algorithm nor its performance.

The name can be confusing if you come to PHP from C, C++, or Go. In C, sizeof is a compile-time operator that reports the memory footprint of a type or structure in bytes. PHP's version counts elements and says nothing about byte allocation. Use memory_get_usage() when inspecting memory consumption, or strlen(serialize($array)) to approximate the size of a serialized payload.

The PHP manual presents count() as the primary name. Stick with it for consistency. A reader unfamiliar with PHP is less likely to mistake it for a measurement of memory usage.

Why count() Operates in O(1) Constant Time

The Zend Engine Hash Table Structure

PHP represents arrays with the zend_array structure, also called a Zend Hash Table. In the PHP C source, this structure has an integer member named nNumOfElements that holds the count.

The Zend Engine maintains that counter as you append elements with $array[] = $value, assign keys with $array['key'] = $value, or remove entries with unset($array['key']). Calling count($array) reads the stored integer directly from the structure in memory. It does not scan the elements to calculate a fresh total. The lookup takes the same constant time whether the array holds five items or five million.

A brass mechanical drum register on a dark wooden workbench beside an open notebook showing a logic flowchart.
// Creating an array with 100,000 elements
$largeArray = range(1, 100000);

// Instantaneous O(1) lookup
$length = count($largeArray);

The Loop Overhead Pitfall

An O(1) lookup still has a cost if you repeat it. Putting count() in the condition of a for loop asks PHP to read the length every time it checks whether the loop should continue:

// Inefficient loop design
$records = range(1, 50000);

for ($i = 0; $i < count($records); $i++) {
    // Loop body executes 50,000 times
}

For 50,000 records, this loop invokes count() 50,001 times. Each call is fast, but those repeated calls still have a cost. Measure a real hot loop before treating this as a meaningful bottleneck.

Store the length in a variable before entering the loop to avoid those repeated calls:

// Optimized loop with cached count
$records = range(1, 50000);
$totalRecords = count($records);

for ($i = 0; $i < $totalRecords; $i++) {
    // The condition does not call count() again
}

When you need to process every element, prefer foreach. It works directly with the array's internal pointers or hash buckets, so you do not have to track an index or check the length yourself:

// Preferred idiomatic PHP
$sum = 0;
foreach ($records as $record) {
    $sum += $record;
}

SPX or Xdebug can show how much CPU time repeated calls consume in a loop. Use a profile to locate the bottleneck and measure the overhead. Our guide to PHP profiling covers ways to isolate these micro-benchmarks in production environments.

Multidimensional Arrays and COUNT_RECURSIVE

For a nested array, decide what you want the result to describe: the number of top-level entries, all entries at every depth, or just the final values. These are different totals.

The Behavior of COUNT_NORMAL

The second argument defaults to COUNT_NORMAL, an integer constant equal to 0. In this mode, each nested array counts as a single element:

$catalog = [
    'books' => ['Fiction', 'Non-Fiction', 'Technical'],
    'magazines' => ['Weekly Digest', 'Monthly Tech'],
    'stationery' => ['Notebooks', 'Pens', 'Pencils', 'Erasers'],
];

echo count($catalog); // Outputs: 3
echo count($catalog, COUNT_NORMAL); // Outputs: 3

There are three top-level keys: books, magazines, and stationery. Adding items inside those sub-arrays does not change how many entries exist at the top level.

Understanding COUNT_RECURSIVE

Pass COUNT_RECURSIVE, or the integer 1, as the second argument to count entries in nested arrays too. Pay attention to what the result includes:

$catalog = [
    'books' => ['Fiction', 'Non-Fiction', 'Technical'],
    'magazines' => ['Weekly Digest', 'Monthly Tech'],
    'stationery' => ['Notebooks', 'Pens', 'Pencils', 'Erasers'],
];

echo count($catalog, COUNT_RECURSIVE); // Outputs: 12

The result is 12, not the 9 you would get by adding only the leaf values (3 books + 2 magazines + 4 stationery items = 9).

PHP includes the container arrays in the total:

  1. Top-level array keys: books, magazines, stationery (3 elements)
  2. Elements inside books: Fiction, Non-Fiction, Technical (3 elements)
  3. Elements inside magazines: Weekly Digest, Monthly Tech (2 elements)
  4. Elements inside stationery: Notebooks, Pens, Pencils, Erasers (4 elements)
  5. Total calculated sum: 3 + 3 + 2 + 4 = 12 elements.

Each branch contributes one along with the leaf nodes beneath it. For another example, three sub-arrays with two items each produce a recursive count of 9 (3 parents + 6 children), not 6.

An open dark walnut box with nested inner wooden trays of decreasing sizes sits beside loose polished glass marbles and brass calipers.

Counting Only Leaf Elements

To count only the final values, use a recursive function that increments its counter when an item is not an array. When it finds an array, it counts the values inside it instead. PHP SPL iterators provide another way to do this:

function countLeafElements(array $items): int
{
    $count = 0;
    foreach ($items as $item) {
        if (is_array($item)) {
            $count += countLeafElements($item);
        } else {
            $count++;
        }
    }
    return $count;
}

$catalog = [
    'books' => ['Fiction', 'Non-Fiction', 'Technical'],
    'magazines' => ['Weekly Digest', 'Monthly Tech'],
    'stationery' => ['Notebooks', 'Pens', 'Pencils', 'Erasers'],
];

echo countLeafElements($catalog); // Outputs: 9

The SPL version combines iterators to flatten the structure before counting its values:

$iterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator($catalog)
);

echo iterator_count($iterator); // Outputs: 9

iterator_count() makes this version concise. Creating the SPL iterator objects adds a little instantiation overhead compared with the plain recursive function.

Guarding Against Circular References

A child element can hold a reference to an ancestor array. That creates a circular reference, and a recursive count can trigger a warning:

$nodeA = [];
$nodeB = [];

$nodeA['child'] = &$nodeB;
$nodeB['parent'] = &$nodeA;

// Triggers: E_WARNING: count(): Recursion detected
$total = count($nodeA, COUNT_RECURSIVE);

The Zend Engine detects the recursion and stops following the loop with an E_WARNING before it exhausts available memory. Avoid recursive counts on complex associative graphs where circular references might occur.

Checking for Empty Arrays: count() Versus empty()

Choose an empty check based on what you know about the variable. A typed array, a nullable value, and a variable that might not exist need different handling.

Comparing count(), empty(), and Boolean Coercion

For an array, these three checks all test whether it contains any items:

$items = [];

// Approach 1: Explicit count check
if (count($items) === 0) {
    // Array is empty
}

// Approach 2: Built-in empty() construct
if (empty($items)) {
    // Array is empty
}

// Approach 3: Direct boolean coercion
if (!$items) {
    // Array is empty
}

All three conditions evaluate to true for an empty array, []. They differ when the variable is undefined or contains null:

  1. empty() checks whether a variable exists and whether its value is falsy. If $items was never defined, empty($items) returns true without a notice or warning. In PHP 8, passing that undefined variable to count($items) emits E_WARNING: Undefined variable $items, then throws a TypeError because the value passed to count() is null. The error is fatal if not caught.
  2. Passing null to count() throws a TypeError in modern PHP; an unhandled error is fatal. empty($items) returns true for a null value.
  3. When a parameter type or property type guarantees an array, !$items or empty($items) is a simple, fast check. Use count() when the actual number matters, such as checking count($items) > 5.

When to Use Strict Comparison with Empty Array

For a strictly typed array, you can also compare directly with an empty array literal:

if ($items === []) {
    // Guarantees $items is an array and has zero elements
}

Strict comparison checks both requirements: $items must be an array, and it must contain no elements. Like empty($items), it avoids a function call; it also avoids relying on truthiness.

Non-Countable Types and the PHP 8 TypeError

The Historical Evolution of Counting

PHP 7.1 and older accepted scalar values and null without a warning. In those releases, count(null) returned 0, while count(42) and count('string') each returned 1. The results could make invalid input look usable.

Suppose a database query or API client failed and returned null where you expected an empty array. count(null) returned 0, hiding the unhandled error behind a plausible count. A string or integer returned 1, so a condition could treat that scalar as a non-empty array.

The RFC on Counting of non-countable types changed that behavior. In PHP 7.2 through 7.4, non-countable arguments produced an E_WARNING.

PHP 8.0 made this a TypeError, as described in the PHP 8.0 backward incompatible changes guide. In PHP 8.0 and later, the argument must be an array or an instance of Countable. Strings, integers, floats, booleans, and null values all cause an error that is fatal if unhandled. You can catch it when diagnosing input:

$value = null;
try {
    count($value);
} catch (TypeError $error) {
    echo $error->getMessage();
}

Defensive Strategies for Nullable Arrays

External APIs, optional database columns, and legacy service classes can return null where the caller expects an array. Handle that possibility before asking for the length.

A solid brass sizing gauge on a rustic workbench with cylindrical dowels passing through circular apertures beside an irregular fragment and a red indicator prism.

Strategy 1: Null Coalescing Operator

For a nullable array, use the null coalescing operator to pass an empty array when the value is null:

$data = null; // A nullable result from an optional payload

$length = count($data ?? []);

When $data is null, this evaluates count([]) and returns 0 without throwing an exception.

Strategy 2: Checking Countability with is_countable()

PHP 7.3 introduced the is_countable() function, which returns true if a variable is an array or an object implementing Countable:

if (is_countable($data)) {
    $length = count($data);
} else {
    $length = 0;
}

This check suits generic libraries and middleware, where incoming data may be an array, a collection object, or an invalid type. It checks whether the value supports counting before the call.

Strategy 3: Strict Static Analysis

Runtime checks can still miss cases. PHPStan can catch non-countable arguments during development, before they reach staging or production. Our tutorial on PHPStan for legacy codebases explains rule levels and baselines for finding variables where null could reach count().

Counting Objects: The Countable Interface

Applications using domain-driven design often keep collections inside dedicated classes. The Countable interface lets callers ask those objects for a count.

Implementing SPL Countable

PHP includes Countable in the Standard PHP Library (SPL). The PHP Countable interface manual defines its single method, count(): int.

When a class implements this interface, count($object) and sizeof($object) call the object's own count method:

class OrderCollection implements Countable
{
    /** @var array<int, array> */
    private array $orders = [];

    public function addOrder(array $order): void
    {
        $this->orders[] = $order;
    }

    public function count(): int
    {
        return count($this->orders);
    }
}

$orders = new OrderCollection();
$orders->addOrder(['id' => 101, 'amount' => 49.99]);
$orders->addOrder(['id' => 102, 'amount' => 85.50]);

echo count($orders); // Outputs: 2

Countable Performance Caveats

For an object, the cost of counting depends on the method implementation. The O(1) guarantee for an ordinary array does not carry over to every Countable class.

A collection might run a SQL SELECT COUNT(*) query or traverse a linked list each time its count method runs. That turns the call into a blocking database roundtrip or an O(n) traversal, rather than a constant-time memory lookup.

Check the implementation before repeatedly counting an object in a loop or validation rule. PHP 8.4 and newer also provide asymmetric visibility and hooks for managing collection counts. Our guide to PHP property hooks in PHP 8.4 covers these ways of encapsulating state.

For syntax refinements that make pipeline operations and array transformations more expressive, see our overview of PHP 8.5 features.

Step-by-Step Guide: Managing Array Length in Practical Applications

A paginated data processor needs counts for several purposes. It first checks the input, then calculates page sizes and offsets. When the records form a grid, it also checks the number of columns in each row.

Step 1: Validating and Normalizing Input Data

Start by checking raw request data against the expected array type:

function normalizePayload(mixed $rawInput): array
{
    if (!is_array($rawInput)) {
        return [];
    }

    return $rawInput;
}

This function always returns an array, so passing its result to count() will not cause a type error.

Step 2: Calculating Pagination Metadata

With an array of records and a requested page size, calculate the total pages, offsets, and number of items on the current page:

function getPaginationMetadata(array $records, int $perPage, int $currentPage): array
{
    $totalItems = count($records);
    $perPage = max(1, $perPage);
    $totalPages = (int) ceil($totalItems / $perPage);
    $currentPage = max(1, min($currentPage, max(1, $totalPages)));

    $offset = ($currentPage - 1) * $perPage;
    $pageItems = array_slice($records, $offset, $perPage);

    return [
        'total_items' => $totalItems,
        'per_page' => $perPage,
        'current_page' => $currentPage,
        'total_pages' => $totalPages,
        'page_items_count' => count($pageItems),
        'items' => $pageItems,
    ];
}

Reading the total with count($records) stays constant-time even with thousands of in-memory records. That part of the pagination calculation does not get slower as the number of records grows.

Step 3: Validating Nested Grid Dimensions

For two-dimensional data, such as a CSV import, check that every row has the expected number of columns:

function validateGrid(array $grid, int $expectedColumns): bool
{
    if (empty($grid)) {
        return false;
    }

    foreach ($grid as $row) {
        if (!is_array($row) || count($row) !== $expectedColumns) {
            return false;
        }
    }

    return true;
}

$matrix = [
    ['id', 'name', 'email'],
    [1, 'Alice', 'alice@example.com'],
    [2, 'Bob', 'bob@example.com'],
];

$isValid = validateGrid($matrix, 3); // Evaluates to true

The comparison count($row) !== $expectedColumns catches missing or extra columns before the records go into storage.