Quick solution
To quickly count the number of elements in a PHP array, we can simply use the count function:
// Source array
$fruits = ['Orange', 'Apple', 'Banana']
// Count the number of elements in $fruits array
echo count( $fruits ); // 3
To count array elements in PHP
The count function is the recommended function to count the number of elements in a PHP array or a Countable object. Beside the count function, sizeof is an alternative function which will deliver the same result.
Using count function
The full count function declaration as Official PHP Documentation:
count(Countable|array $value, int $mode = COUNT_NORMAL): int
$valueis the array or Countable object to be counted.$modeis the count mode, which can be adjusted to enable counting recursive array.
Default value isCOUNT_NORMAL.
Count recursive array
The $mode parameter by default, COUNT_NORMAL, can only count non-recursive array. To count all elements including the recursive (or nested) array elements, set the $mode parameter as COUNT_RECURSIVE:
count( $array, COUNT_RECURSIVE );
Example of counting recursive array:
// Source array
$food = ['fruits' => ['Orange', 'Apple', 'Banana'],
'veggie' => ['Carrot', 'Collard', 'Pea']];
// Normal count mode
echo count( $food ); // 2
// Recursive count mode
echo count( $food, COUNT_RECURSIVE ); // 8
Using sizeof function
The sizeof function is an alias of count, and does the same functionality:
// Source array
$fruits = ['Orange', 'Apple', 'Banana']
// Count using sizeof function
echo sizeof( $fruits ); // 3
Final thoughts
It is easy and straightforward to count array elements in PHP, which can be used by either count or sizeof function. The count function is used more and is recommended as better human readable keyword.




