PHP Tutorial - PHP Array foreach loop






foreach is a special kind of looping statement that works only on arrays and objects.

foreach can be used in two ways.

  • retrieve just the value of each element, or
  • retrieve the element's key and value.

Syntax to get value

Use foreach to retrieve each element's value, as follows:

foreach ( $array as $value ) { 
   // (do something with $value here) 
} 
// (rest of script here)   




Syntax to get key and value

To use foreach to retrieve both keys and values, use the following syntax:

foreach ( $array as $key =>  $value ) { 
   // (do something with $key and/or $value here 
} 
// (rest of script here)   

Example 1

Use foreach loop to get value


<?PHP
   $authors = array( "Java", "PHP", "CSS", "HTML" ); 

   foreach ( $authors as $val ) { 
       echo $val . "\n"; 
   }   
?>

The code above generates the following result.





Example 2

Use foreach to loop through associate array


<?php //from   ww w  .  ja  va2s .  c o m
$myBook = array( "title" =>  "Learn PHP from java2s.com", 
                "author" =>  "java2s.com", 
                "pubYear" =>  2000 ); 

foreach ( $myBook as $key =>  $value ) { 
   echo "$key  \n"; 
   echo "$value \n"; 
} 

?>

The code above generates the following result.

PHP Change Array Values with foreach

When using foreach, the values inside the loop are copies of the values.

If you change the value, you're not affecting the value in the original array. The following example code illustrates this:


<?PHP/*www .j a  va  2  s. c  o  m*/
$authors = array( "Java", "PHP", "CSS", "HTML" ); 

// Displays "Java PHP Javascript HTML"; 
foreach ( $authors as $val ) { 
   if ( $val == "CSS" ) $val = "Javascript"; 
   echo $val . " "; 
} 

print_r ( $authors );   
?>

The code above generates the following result.

Although $val was changed from "CSS" to "Javascript" within the loop, the original $authors array remains untouched.

How

To modify the array values, we need to get foreach() to return a reference to the value in the array, rather than a copy.

Syntax

To work with references to the array elements, add a &(ampersand) symbol before the variable name within the foreach statement:

foreach ( $array as & $value ) {

Example

Here's the previous example rewritten to use references:


<?PHP
 $authors = array( "Java", "PHP", "CSS", "HTML" ); 
 foreach ( $authors as  & $val ) { 
   if ( $val == "CSS" ) $val = "Javascript"; 
   echo $val . " "; 
 } 
 unset( $val ); 
 print_r ( $authors );   
?>

The code above generates the following result.

This time, the third element's value in the $authors array is changed from "CSS" to "Javascript" in the array itself.

Note

The unset($val) ensures that the $val variable is deleted after the loop has finished.

When the loop finishes, $val still holds a reference to the last element. Changing $val later in our code would alter the last element of the $authors array. By unsetting $val, we avoid potential bug.