PHP Change Array Values with foreach
In this chapter you will learn:
- Why the value is not changed in foreach loop
- How to change the value inside a foreach loop
- Syntax to get value reference in a foreach loop
- Example - change array value with reference in foreach loop
- 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:
- What is multidimensional array
- Example for a multidimensional array
- Example - Create two-dimensional array with array() function