How to Count Elements in a PHP Array

Counting the number of elements in an array is a fundamental task in PHP development. This article explains the primary PHP functions used for this purpose, demonstrates their basic usage with clear code examples, and explains how to count elements in multidimensional arrays.

The count() Function

The standard and most common function used to count elements in a PHP array is count().

Syntax

count(mixed $value, int $mode = COUNT_NORMAL): int

Basic Example

In a standard, single-dimensional array, count() returns the number of elements:

<?php
$fruits = ['apple', 'banana', 'cherry', 'date'];
$total_fruits = count($fruits);

echo $total_fruits; // Outputs: 4
?>

Counting Multidimensional Arrays

When dealing with nested arrays, a normal count only counts the top-level elements. To count all elements, you must use the recursive mode.

Example: Normal vs. Recursive Count

<?php
$food = [
    'fruits' => ['apple', 'banana'],
    'veggies' => ['carrot', 'spinach', 'broccoli']
];

// Normal count (only counts top-level keys: 'fruits' and 'veggies')
echo count($food); // Outputs: 2

// Recursive count (counts the 2 sub-arrays + the 5 inner elements)
echo count($food, COUNT_RECURSIVE); // Outputs: 7
?>

The sizeof() Function

PHP also offers the sizeof() function. This function is an alias of count(). It performs the exact same utility and accepts the same parameters.

<?php
$cars = ['Volvo', 'BMW', 'Toyota'];
echo sizeof($cars); // Outputs: 3
?>

While sizeof() works identically, using count() is generally preferred in the PHP community as it more clearly describes the action being performed.