Arrays7 min readExamples run on PHP 8.5.10

sizeof()

Learn how PHP sizeof() works as an alias of count(), including its parameters, return value, recursive mode, TypeError cases and common mistakes.

Signature

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

Purpose

sizeof() reports how many elements a container holds. It is an alias of count(): the two names call the same function, so they accept the same arguments, return the same results and fail in the same ways. Anything you learn about one applies to the other.

Most modern PHP code uses count(), because sizeof() can suggest a C-style "size in bytes" meaning that it does not have. sizeof() still works in PHP 8.4, and you will meet it in older code bases, so it helps to read it fluently.

Signature

Parameters and defaults

  • $value: an array, or an object that implements the Countable interface. This is required.
  • $mode: optional. The default COUNT_NORMAL counts only the elements at the top level. COUNT_RECURSIVE also walks into nested arrays and counts their elements.

Return value and failure cases

The function returns an int: the number of elements. An empty array gives 0.

If $value is neither an array nor a Countable object, PHP 8.4 throws a TypeError. This covers null, strings, integers, booleans and plain objects that do not implement Countable. The function does not quietly return 1 or 0 for those values.

Example 1: counting a list

The simplest use is asking how many items an array holds.

Example
<?php
$items = ['apple', 'banana', 'cherry'];
echo sizeof($items), "\n";
echo sizeof([]), "\n";
Output
3
0

The first call prints 3 and the empty array prints 0. Keys do not matter: an associative array is counted the same way as a list.

Example 2: recursive counting

With COUNT_RECURSIVE, each nested array counts as one element and so do all the elements inside it.

Example
<?php
$menu = [
    'fruit' => ['apple', 'pear'],
    'veg' => ['kale'],
];
echo json_encode([sizeof($menu), sizeof($menu, COUNT_RECURSIVE)]), "\n";
Output
[2,5]

The top level has two elements, fruit and veg. The recursive count adds the two fruits and one vegetable, giving five.

Example 3: Countable objects and invalid values

A class can decide what its own count means by implementing Countable. Its count() method is called when you pass an instance to sizeof().

Example
<?php
class Basket implements Countable
{
    public function __construct(private array $items)
    {
    }

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

$basket = new Basket(['a', 'b', 'c', 'd']);
echo sizeof($basket), "\n";

try {
    echo sizeof('hello');
} catch (TypeError $e) {
    echo "TypeError\n";
}
Output
4
TypeError

The basket reports four items. Passing a string is not allowed, so the TypeError is caught and reported.

Edge cases

  • An empty array returns 0, which is falsy. Writing if (sizeof($list)) is a valid way to ask whether the array has any elements.
  • Nested arrays count as one element in normal mode, no matter how many items they contain.
  • COUNT_RECURSIVE counts both the nested arrays themselves and the elements within them, so the total is larger than the number of leaf values.
  • For a Countable object, the result is whatever its count() method returns. The class author is responsible for making that value meaningful.
  • null is not treated as an empty array. If a variable might be null, check it or provide a default before counting.

Common mistakes

  1. Counting a string. sizeof('hello') does not return 5. It throws a TypeError. Use strlen() for the byte length of a string.
  2. Expecting bytes. The name resembles the C operator, but the function counts elements, not memory.
  3. Forgetting recursion is opt-in. Without COUNT_RECURSIVE, nested content is not included in the total.
  4. Misreading the recursive total. The number includes the nested array entries too, so it is not simply the number of scalar values.
  5. Passing a possibly missing value. Results from functions that can return null or false should be validated before they reach sizeof().
  6. Counting a non-countable object. Generators and plain objects are not Countable, so they throw a TypeError. Convert a generator to an array first if you need its length, and only when that is safe for your data size.
  • count(): the main name for this function. Prefer it in new code.
  • strlen(): the length of a string in bytes.
  • array_key_exists() and isset(): check for specific keys rather than totals.
  • empty(): a quick check for an empty array.
  • array_sum(): adds values together, which is different from counting them.

Recap

sizeof() is another name for count(). It takes an array or a Countable object, accepts an optional mode, and returns an integer. Use COUNT_RECURSIVE only when you want nested elements included, and expect a TypeError for anything that cannot be counted. In new code, count() is the clearer choice, but both behave identically.

Tested examples

Counting a list
<?php
$items = ['apple', 'banana', 'cherry'];
echo sizeof($items), "\n";
echo sizeof([]), "\n";
Output
3
0
Recursive counting
<?php
$menu = [
    'fruit' => ['apple', 'pear'],
    'veg' => ['kale'],
];
echo json_encode([sizeof($menu), sizeof($menu, COUNT_RECURSIVE)]), "\n";
Output
[2,5]
Countable objects and invalid values
<?php
class Basket implements Countable
{
    public function __construct(private array $items)
    {
    }

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

$basket = new Basket(['a', 'b', 'c', 'd']);
echo sizeof($basket), "\n";

try {
    echo sizeof('hello');
} catch (TypeError $e) {
    echo "TypeError\n";
}
Output
4
TypeError