PHP Change Array Values with foreach

In this chapter you will learn:

  1. Why the value is not changed in foreach loop
  2. How to change the value inside a foreach loop
  3. Syntax to get value reference in a foreach loop
  4. Example - change array value with reference in foreach loop
  5. Note for unset value

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  j  a v a2 s  .co  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//from   j a v  a2s .com
 $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.

Next chapter...

What you will learn in the next chapter:

  1. What is multidimensional array
  2. Example for a multidimensional array
  3. Example - Create two-dimensional array with array() function
Home » PHP Tutorial » PHP Array
PHP Array
PHP Create Indexed Array
PHP Create Associative Arrays
PHP Array Operator
PHP Access Array Element
PHP Change Array Element
PHP Create Array using Square Bracket
PHP Array Element Loop Through
PHP Array foreach loop
PHP Change Array Values with foreach
PHP Array Multidimensional
PHP Access Element in Multidimensional Array
PHP Loop Through Multidimensional Array