Web Development Tutorials




  
  

For-Each Loop

The foreach construct is a variation of the for loop and is used to iterate over arrays. There are two different versions of the foreach loop.

The basic foreach loop syntaxes are shown below:

  foreach (array as $value) {
    statement
  }
    
  foreach (array as $key => $value) {
    statement
  }

The first type of foreach loop is used to loop over an array denoted by array. During each iteration through the loop, the current value of the array is assigned to the variable - $value and the loop counter is incremented by a value of one. Looping continues until the foreach loop reaches the last element or upper bound of the given array. During each loop, the value of the variable - $value can be manipulated but the original value of the array remains the same.

The following example demonstrates how the foreach loop is used to iterate over the values of an array:

<?php 
  
  $my_array = array('red','green','blue');
  
  $colors = ""; // declare $colors string variable
	
  echo "The different colors include: ";

  foreach($my_array as $value) {
    $colors .= $value . " ";	
  }

  echo $colors;

?>	

During each loop, the color name associated with the current array element is assigned to a variable - $colors. A single space " " is also added between each of the color names for display purposes. When the loop reaches the end of the array, the output below is generated:

  The different colors include: red green blue 

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

<?php 
  
  $my_array = array('red', 'green', 'blue');
  foreach ($my_array as &$value) {
      if ($value == 'blue') {
		 $value = 'yellow';
	  }
  }
  // $my_array is now array('red', 'green', 'yellow')
  unset($value); // break the reference with the last element

?>	

The second form of the loop provides the same functionality as the first, but also assigns the current array element's index or key to be assigned to the variable - $key on each loop. In the previous example, the array $my_array contains three elements: $my_array[0] = "red", $my_array[1] = "green", and $my_array[2] = "blue". While the variable - $value contains the array element values: red, green, and blue, the variable $key contains the array element indices: 0, 1, and 2.

The following example demonstrates how the foreach loop is used to iterate over the values of an array using the second form:

<?php 
  
  $my_array = array('red','green','blue');
  
  $colors = ""; // declare $colors string variable
	
  echo "The different colors include: ";

  foreach($my_array as $key => $value) {
    $colors .= $my_array[$key] . " ";	
  }

  echo $colors;

?>	

TOP | NEXT: Chapter 6 - Reusing Code & Functions