Skip to content

PHP Tutorial Arrays

Counting Arrays

Lesson 122 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

count() tells you how many items an array holds.

index.php
PHP
<?php
$fruits = ["apple", "banana", "cherry"];

echo count($fruits);
Output
OUTPUT
3

sizeof() is an alias of count(). Use count(), which is the usual name.

Works with associative arrays

index.php
PHP
<?php
$user = ["name" => "Isha", "city" => "Kochi"];

echo count($user);
Output
OUTPUT
2

Is the array empty?

index.php
PHP
<?php
$cart = [];

if (count($cart) === 0) {
    echo "Cart is empty\n";
}

if (empty($cart)) {
    echo "Still empty\n";
}

if ($cart === []) {
    echo "Also empty";
}
Output
OUTPUT
Cart is empty
Still empty
Also empty

All three work for arrays. empty() and === [] also work if the variable might not exist.

Counting nested arrays

By default, count() counts only the top level.

index.php
PHP
<?php
$data = [1, [2, 3], [4, [5, 6]]];

echo count($data) . "\n";
echo count($data, COUNT_RECURSIVE);
Output
OUTPUT
3
9

The recursive count includes the inner arrays themselves and every value inside them: the values 1 to 6 (six items) plus the three arrays make nine.

Count how often each value appears

index.php
PHP
<?php
$votes = ["yes", "no", "yes", "yes", "no"];

print_r(array_count_values($votes));
Output
OUTPUT
Array
(
    [yes] => 3
    [no] => 2
)

Count items that match a rule

index.php
PHP
<?php
$ages = [12, 18, 25, 9, 40];

$adults = count(array_filter($ages, fn($age) => $age >= 18));

echo $adults;
Output
OUTPUT
3

count() only works on arrays and Countable objects

Passing a string or null to count() throws a TypeError in PHP 8. Check the type first if you are not sure.

index.php
PHP
<?php
try {
    echo count("hello");
} catch (TypeError $e) {
    echo $e->getMessage();
}
Output
OUTPUT
count(): Argument #1 ($value) must be of type Countable|array, string given
lightbulb
Average of an array
array_sum($a) / count($a) is the average. Check that the array is not empty first, to avoid dividing by zero.