count() tells you how many items an array holds.
<?php
$fruits = ["apple", "banana", "cherry"];
echo count($fruits);
3
sizeof() is an alias of count(). Use count(), which is the usual name.
Works with associative arrays
<?php
$user = ["name" => "Isha", "city" => "Kochi"];
echo count($user);
2
Is the array empty?
<?php
$cart = [];
if (count($cart) === 0) {
echo "Cart is empty\n";
}
if (empty($cart)) {
echo "Still empty\n";
}
if ($cart === []) {
echo "Also empty";
}
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.
<?php
$data = [1, [2, 3], [4, [5, 6]]];
echo count($data) . "\n";
echo count($data, COUNT_RECURSIVE);
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
<?php
$votes = ["yes", "no", "yes", "yes", "no"];
print_r(array_count_values($votes));
Array
(
[yes] => 3
[no] => 2
)
Count items that match a rule
<?php
$ages = [12, 18, 25, 9, 40];
$adults = count(array_filter($ages, fn($age) => $age >= 18));
echo $adults;
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.
<?php
try {
echo count("hello");
} catch (TypeError $e) {
echo $e->getMessage();
}
count(): Argument #1 ($value) must be of type Countable|array, string given
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.