How to use PHP’s foreach construct to loop through PHP array elements.
Often you need to move through all the elements in a PHP array so that you can do something with each element’s value. For example, you may want to display each value in an HTML table, or give each element a new value.
In Counting PHP Array Elements Using
count(), I showed how you can use a for loop along with thecount() function to loop through an array. However, there’s a much easier way to loop through arrays: theforeach construct.
In this article you learn the basic syntax of
foreach, and see how to use it to loop through both indexed and associative arrays.Looping through element values
The simplest way to use
foreach is when looping through the values in an indexed array. Here’s the basic syntax:foreach ($arrayas$value) {// Do stuff with$value}// This code runs after the loop finishes
For example, the following script loops through a list of movie directors in an indexed array, displaying each director’s name as it goes:
<?php
$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" );
foreach ( $directors as $director ) {
echo $director . "<br />";
}
?>
The above script produces the following output:
Alfred Hitchcock Stanley Kubrick Martin Scorsese Fritz Lang
Looping through keys and values
So far so good, but what about associative arrays? With these types of arrays, you often want to access each element’s key as well as its value. Luckily,
foreach gives you a way to do just that:foreach ($arrayas$key=>$value) {// Do stuff with$keyand/or$value}// This code runs after the loop finishes
Here’s an example that loops through an associative array of movie information, displaying each element’s key and value inside an HTML definition list:
<?php
$movie = array( "title" => "Rear Window",
"director" => "Alfred Hitchcock",
"year" => 1954,
"minutes" => 112 );
echo "<dl>";
foreach ( $movie as $key => $value ) {
echo "<dt>$key:</dt>";
echo "<dd>$value</dd>";
}
echo "</dl>";
?>
This script displays the following:
title:Rear Windowdirector:Alfred Hitchcockyear:1954minutes:112
Altering element values
So far you’ve just looked at reading element values, but what if you want to change values as you loop through? You might try something like this:
<?php
foreach ( $myArray as $value ) {
$value = 123;
}
?>
However, if you do this you’ll find that your array values aren’t changed. This is because
foreach works on acopy of the array values, rather than the original array. So the original array remains untouched.
To change array values, you need to reference the values. You do this by placing an ampersand (
&) before the value variable in the foreach construct:<?php
foreach ( $myArray as &$value ) {
$value = 123;
}
?>
$value then becomes a reference to the element value in the original array, which means you can change the element by assigning a new value to $value.
A reference is a pointer to the original value, rather than a copy of the value. It’s a bit like a shortcut in Windows, or an alias in Mac OS.
For example, the following script loops through each director in the
$directors array, and uses PHP’sexplode() function and list construct to reverse the director’s first and last names:<?php
$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" );
// Change the name format for each element to "last, first"
foreach ( $directors as &$director ) {
list( $firstName, $lastName ) = explode( " ", $director );
$director = "$lastName, $firstName";
}
unset( $director );
// Output the final array
foreach ( $directors as $director ) {
echo $director . "<br />";
}
?>
This script outputs the following:
Hitchcock, Alfred
Kubrick, Stanley
Scorsese, Martin
Lang, Fritz
Hitchcock, Alfred
Kubrick, Stanley
Scorsese, Martin
Lang, Fritz
Notice that the script calls unset() to delete the $director variable after it’s been used as a reference in the first loop. This is always a good idea if you think you might want to use the variable later in the script in a different context.
If you don’t delete the reference then you run the risk of accidentally referencing the last element in the array (“Lang, Fritz”) when you next use the $director variable, with often quite unexpected consequences!
Note: In case you’re wondering, you can only change array <em>values</em> in a foreach loop. You can’t change array keys
0 comments:
Post a Comment