PHP Change Array Values with foreach

Background

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//from w  ww . j  a v a  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/*  ww  w.jav a 2  s  . c om*/
 $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.





















Home »
  PHP Tutorial »
    Data Types »




Array
Array Associative
Array Util
ArrayObject
Data Types
Date
Date Format
DateTime
Number
String
String Escape
String Filter
String HTML
String Type
Timezone