How to use a loop In PHP

To count all array elements in PHP using a loop, initialize a counter variable to zero. Iterate through the array elements using a loop and increment the counter for each element. The final count represents the total number of elements.

Example

PHP
<?php
// Single-dimensional array
$array = array("Geek1", "Geek2", "Geek3", "1", "2", "3");  
$count = 0;
foreach ($array as $element) {
    $count++;
}
echo "Count first array elements: $count \n";

// Multi-dimensional array
$array = array(
    'names' => array("Geek1", "Geek2", "Geek3"), 
    'rank' => array('1', '2', '3')
); 

// Recursive count
$count = 0;
foreach ($array as $subarray) {
    foreach ($subarray as $element) {
        $count++;
    }
}
echo "Recursive count: $count \n";

// Normal count
echo "Normal count: " . count($array) . "\n"; 
?>

Output
Count first array elements: 6 
Recursive count: 6 
Normal count: 2

How to count all array elements in PHP ?

We have given an array containing some array elements and the task is to count all elements of an array arr using PHP. In order to do this task, we have the following methods in PHP:

Table of Content

  • Using count() Method
  • Using sizeof() Method
  • Using a loop
  • Using iterator_count with ArrayIterator

Similar Reads

Using count() Method

The count() method is used to count the current elements in an array. It returns 0 for an empty array....

Using sizeof() Method

The sizeof() method is used to count the number of elements present in an array or any other countable object....

Using a loop

To count all array elements in PHP using a loop, initialize a counter variable to zero. Iterate through the array elements using a loop and increment the counter for each element. The final count represents the total number of elements....

Using iterator_count with ArrayIterator

Using iterator_count with ArrayIterator involves wrapping the array in an ArrayIterator object, which provides a way to traverse the array. The iterator_count function then counts the elements of this iterator, giving the total number of elements in the array....

Contact Us