How to count all array elements in PHP ?


In PHP, we can count all the elements of an array using the count() function.

Syntax:

count($array);

Example:

$fruits = array("apple", "banana", "orange", "mango");
$count = count($fruits);
echo "Total number of fruits: " . $count;

Output:

Total number of fruits: 4

Another method to count all the elements of an array is to use a foreach loop and increment a counter variable for each iteration.

Example:

$fruits = array("apple", "banana", "orange", "mango");
$count = 0;
foreach($fruits as $fruit){
    $count++;
}
echo "Total number of fruits: " . $count;

Output:

Total number of fruits: 4


About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.