How to Count All Elements in an Array with the PHP count() Function

09/04/2021

Contents

In this article, you will learn how to count all elements in an array with the PHP count() function.

PHP count() function

The count() function returns the number of elements in the array.

Syntax:

count($array, [$mode])

Enter COUNT_RECURSIVE in $mode to count elements recursively. This parameter can be omitted if not used.

Sample

Sample Code

<?php
$arr1 = array(1,2,3);
$arr2 = array("a","b","c");
$arr3 = array($arr1,$arr2);
$arr4 = array(4,5,$arr1);

echo count($arr1);
echo "<br>";
echo count($arr3);
echo "<br>";
echo count($arr3,COUNT_RECURSIVE);
echo "<br>";
echo count($arr4,COUNT_RECURSIVE);
?>

Result

3
2
8
6