Categories
PHP

Array Iteration

The easiest way to iterate through each element of an array is with foreach. The foreach statement lets you run a code block once for each element in an array.

  1. Looping arrays with ForEach statement
  2. Looping a numerical array with For statement
  3. Using print_r function
  4. Looping a Multidimensional or Nested Array using a Recursive Function.

Iterate Arrays with ForEach Loop

As we discussed earlier, the easiest way to iterate through an array is using the foreach statement. The foreach statement has two forms, both iterate through an array expression, executing the body of the loop for each element in the array:

foreach(array_expression as $value) statement
foreach(array_expression as $key => $value) statement

The first form assigns the value from the element to a variable identified with the as keyword; the second form assigns both the key and the value to a pair of variables.

The following example shows the first form in which the array expression is the variable $lengths, and each value is assigned to the variable $cm:

<?php
// Construct an array of integers
$lengths = array(0, 107, 202, 400, 475);

// Convert an array of centimeter lengths to inches
foreach($lengths as $cm) {
  $inch = $cm / 2.54;
  echo "$cm centimeters = $inch inches\n";
} 

The example iterates through the array in the same order it was created:

0 centimeters = 0 inches
107 centimeters = 42.125984251969 inches
202 centimeters = 79.527559055118 inches
400 centimeters = 157.48031496063 inches
475 centimeters = 193.87755102041 inches

The first form of the foreach statement can also iterate through the values of an associative array, however the second form assigns both the key and the value to variables identified as $key => $value. The next example shows how the key is assigned to $animal, and the value is assigned to $sound to generate verses of “Old MacDonald”:

<?php
$sounds = ["cow"=>"moo", "dog"=>"woof", "duck"=>"quack"];
foreach ($sounds as $animal => $sound) {
  echo "<p>A $animal sounds: $sound</p>";
}

This prints a verse for each $animal/$sound pair in the $sounds array:

A cow sounds: moo
A dog sounds: woof
A duck sound: quack

Looping through numerical arrays can most easily be done using foreach because in each iteration of the loop, the current element in the array is automatically written in a variable.

<?php
  $a = ['I', 'II', 'III', 'IV';
  foreach ($a as $element) {
    echo $element . '<br>';
  }

When the second form of the foreach statement is used with a nonassociative (numerical) array, the index is assigned to the key variable and the value to the value variable. The following example uses the index to number each line of output:

<?php
 // Construct an array of integers
 $lengths = array(0, 107, 202, 400, 475);

 // Convert an array of centimeter lengths to inches
 foreach($lengths as $index => $cm) {
  $inch = $cm / 2.54;
  echo "$index:  $cm centimeters = $inch inches\n";
 }

Alternatively, a for loop can also be used. The first array element has the index 0; the number of array indices can be retrieved using the count() function.

Iterate or Looping Through an Array with for

<?php
  $a = array('I', 'II', 'III', 'IV');
  for ($i = 0; $i < count($a); $i++) {
    echo $a[$i] . '<br>';
  }

The for loop is equally good for numerical arrays; though, usually, using foreach is the much more convenient way.

Nested arrays can be printed really easily by using print_r(). Take a look at the output of the listing in the figure.

<?php
 $roman = ['one' => 'I', 'two' => 'II', 'three' => 'III'];
 $arabic= ['one' => '1', 'two' => '2', 'three' => '3'];
 
 $a = array('Roman'  => $roman, 'Arabic' => $arabic);
 print_r($a);
Printing array contents with print_r().

If you set the second parameter of print_r() to true, the array’s contents are not sent to the browser, but are returned from the function, so that you can save this information in a variable and process it further.

However, the output of the preceding code is hardly usable for more than debugging purposes. Therefore, a clever way to access all data must be found.

Looping a Multidimensional or Nested Array using a Recursive Function

A recursive function is a reasonable way to achieve this. In this, all elements of an array are printed out; the whole output is indented using the HTML element <blockquote>. If, however, the array element’s value is an array itself, the function calls itself recursively, which leads to an additional level of indention. Whether something is an array can be determined using the PHP function is_array(). Using this, the following code can be assembled.

<?php
  function printNestedArray($a) {
    echo '<blockquote>';
    foreach ($a as $key => $value) {
      echo "$key: ";
      if (is_array($value)) {
        printNestedArray($value);
      } else {
        echo "$value <br>";
      }
    }
    echo '</blockquote>';
  }

 $roman = ['one' => 'I', 'two' => 'II', 'three' => 'III'];
 $arabic= ['one' => '1', 'two' => '2', 'three' => '3'];
 
 //Nested/Multidimensional Array
 $arr = array('Roman'  => $roman, 'Arabic' => $arabic);
 
 //Call function to print array
 printNestedArray($arr);

See the figure for the result:

Printing array contents using a recursive function.

Working with arrays: