Quick solution

To quickly count the number of elements in a PHP array, we can simply use the count function:

PHP

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:

PHP

  • $value is the array or Countable object to be counted.
  • $mode is the count mode, which can be adjusted to enable counting recursive array.
    Default value is COUNT_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:

PHP

Example of counting recursive array:

PHP

Using sizeof function

The sizeof function is an alias of count, and does the same functionality:

PHP

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.