How to Count all Elements in an Array in PHP

Finding the count of all the elements in an array is a common programming task. PHP provides two built-in utilities for getting the total number of value in an array; count() and sizeof().

 

Using count()

To use the count() utility, pass the array inside the () (parenthesis) and store the result in a variable.

 

$fruit = ['strawberry', 'orange', 'apple'];

$total = count($fruit);

var_export($total);
3

 

Using sizeof()

sizeof() has the same behaviour as count() except sizeof() has a slower execution time, making count() the preferable option.

 

$fruit = ['strawberry', 'orange', 'apple'];

$total = sizeof($fruit);

var_export($total);
3

 

Prevent Errors When Counting in PHP

Both sizeof() and count() will throw an error if the variable supplied is not an array. To prevent errors happening we can check if the variable to count is an array using an if statement with the PHP is_array() utility.

 

$fruit = ['strawberry', 'orange', 'apple'];

if (is_array($fruit)) {
  // is an array, do somthing...

  $total = count($fruit);

  var_export($total);

} else {
  // not an array do something else...
}

 

Count and Display Each Value

To display the count of each element as well as its value we can use a foreach loop and a count variable, which will increment on each iteration.

 

$fruit = ['strawberry', 'orange', 'apple'];

if (is_array($fruit)) {
  // is an array, do somthing...

  $count = 1; //start count at 1.

  foreach ($fruit as $f) {
     echo $count .' '. $f .'<br>';
     $count++;
  }
}

 

Conclusion

You now know how to get the total of all the elements in an array in PHP.

count array length