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