Unleash the Power of Each: Embrace the Foreach!
You can use the for loop to iterate through an array, but to really shine, you need to use the foreach loop. The foreach loop has the following syntax.
foreach ($array as $key => $value)
You’ll read the structure like this:
- For each array as key/value … or
- For each key/value pair inside of an array.
It means that the foreach loop will loop through each array element and you will have access to each key/value pair of each element. This is great if you’re dealing with associative arrays. If the key is a string, you will not be able to access the element with a numerical index.
Sometimes you also need to display the key. For example, let’s say that you’re storing a to-do list inside of an associative array, where each key is the day of the week. You may need to display the key to the user as well. If you don’t, the structure of the foreach statement can be reduced.
foreach ($array as $value)
The above structure will only provide you access to the element’s value. You still have the advantage of looping through an array that has either non-numerical keys, or numerical but non-consecutive keys.
Let’s look at an example of the foreach loop iterating through a normal array that has numerical indices.
$things_to_buy = [
"meat shredder claws",
"taco sleeping bag",
"tortilla toaster",
"the keyboard waffle iron"
];
// for loop
for ( $i = 0; $i < count($things_to_buy); $i++ ) {
echo $things_to_buy[$i] . "<br>";
}
// foreach( $array as $array_value ) { loop body }
foreach ( $things_to_buy as $value ) {
echo $value . "<br>";
}
?>
We could use the for loop to loop through the array, or we could go with the foreach loop.
As you can see from the example above, with the foreach loop, the syntax is a lot simpler. We don’t have to use the count() function to get the number of elements inside of the array. We also don’t have to use a counter variable ($i) to keep track of which index we’re on. PHP does all of that for us when we use the foreach loop.
Examining the example above, PHP:
- Encounters the foreach statement. It knows that it will be iterating through an array.
- The syntax inside of the foreach loop says that each array element value will be accessed.
- During the first iteration, PHP has access to the first element. When the echo statement is executed, the $value variable points to the first element inside of the array. So, PHP displays “meat shredder claws.”
- PHP reaches the end of the loop body and repeats the process until there are no more elements in the array.
With the foreach statement, you don’t have to worry about whether the index value that you selected is going to be out-of-bounds. PHP will keep track of that for you.
The $key and $value elements inside of the foreach loop structure do not have to be named key/value. You can name them whatever you like. For example, let’s say that we have an array of cars. Instead of naming the element $value, we could name it $car and be explicit as to what that value represents.
$cars = [ "EVO", "STi", "Supra", "Skyline" ]; foreach( $cars as $car ) { echo $car . "<br>"; } ?>
That’s a lot easier to read than if we used a for loop or if we simply said $value instead of $car.
Let’s implement the to-do list example that was mentioned earlier. This time, we’re going to need access to both the key and the value. We can name the key/value pair as $key/$value or we can be explicit with our naming. The key stores the day of the week, and the value stores the to-do item. We’ll name the key $day_in_week and we’ll name the value $to_do_item.
// foreach( $array as $key => $value ) { Loop body }
$to_do_list = [
"Monday" => "Eat vanilla pudding out of a mayo jar.",
"Tuesday" => "Photoshop waldo out of where's waldo and send them to friends.",
"Wednesday" => "Go to the Apple store and order a Big Mac.",
"Thursday" => "Go to SeaWorld with a fishing pole.",
"Friday" => "Quit my job.",
"Saturday" => "Try to be more responsible.",
"Sunday" => "Panic because nobody's subscribing."
];
foreach ( $to_do_list as $day_in_week => $to_do_item ) {
echo $day_in_week . ": " . $to_do_item . "<br>";
}
?>
When we loop through the $to_do_list array, we have access to both the key and the value. PHP will display the content of the key, followed by a colon, followed by the content of the value for each element in the array. Remember that the foreach structure requires that you use the as keyword, and the arrow (=>) inside of the foreach statement if you’re accessing the key/value pairs.
PHP Tutorial Series
Continue your learning with these articles
LOOP IT UP: UNLEASH THE POWER OF FOR LOOPS!
I use for loops way more than I use while loops. It seems like most of the time I’m reading items from a database: for loops are perfect for that.
Unleash the Power of Each: Embrace the Foreach!
You can use the for loop to iterate through an array, but to really shine, you need to use the foreach loop. PHP allows you to foreach through arrays.
Unleash the Power of Each: Embrace the Foreach!
PHP – P33: break statement
We looked at the break statement when we covered switch statements. In that case, the break statement was used to end the execution of the switch statement. The break statement isn’t exclusive to the switch statement: it can be used in loops as well.