Iterating associative arrays
Learn to walk both keys and values with foreach.
Key and value with foreach
To walk both the keys and the values of an associative array together use foreach ($arr as $key => $value). On each step the variables $key and $value hold the current pair.
For example foreach ($user as $k => $v) { echo "$k: $v"; } walks each key-value pair in turn and prints it. PHP keeps associative arrays in insertion order; the loop runs in that order.
Printing pairs in order
While walking an associative array you can format each pair as you like. Inside double quotes "$key: $value" makes PHP insert the variables automatically; this is called variable interpolation.
Adding \n at the end of each line keeps the output readable. Since an associative array preserves insertion order the loop output follows that order; this is useful when showing a list to a user.
Exercise List the grades
Create the $grades associative array with "math" => 85, "physics" => 78, "chemistry" => 92. Use foreach to print each key-value pair as math: 85, one per line.
Show example solution
$score\n"; }
Example solution:
<?php
// List the grades
$grades = ["math" => 85, "physics" => 78, "chemistry" => 92];
foreach ($grades as $subject => $score) {
echo "$subject: $score\n";
}
Test yourself
-
Which foreach walks both key and value?
- foreach ($user as $value)
- foreach ($user as $key => $value)
- foreach ($user as $key -> $value)
- foreach ($user => $key, $value)
Show answer
foreach ($user as $key => $value) — Correct. The as $key => $value form gives both.
-
Write the foreach keyword
foreach ($user ____ $key => $value) { echo "$key: $value\n"; }Show answer
foreach ($user as $key => $value) { echo "$key: $value\n"; } -
Match each syntax to its meaning
- foreach ($a as $v)
- value only
- foreach ($a as $k => $v)
- key and value
- $a["x"]
- single value access