PHP Associative Arrays
Map names to values and loop over keys and values.
PHP
<?php
$scores = ["Ada" => 91, "Grace" => 88];
$scores["Linus"] = 79;
foreach ($scores as $name => $score) {
echo "$name: $score\n";
}
echo count($scores), "\n";Output
Ada: 91 Grace: 88 Linus: 79 3
Explanation
A PHP array is an ordered map. With string keys it works as a dictionary: ["Ada" => 91] pairs the key with a value, and $scores["Linus"] = 79 adds one more entry at the end.
foreach ($scores as $name => $score) gives the loop both the key and the value. Variables inside a double-quoted string are replaced with their values, and count returns the number of entries.
Explore the dry run
Guided walkthroughReady
1
<?php2
$scores = ["Ada" => 91, "Grace" => 88];3
$scores["Linus"] = 79;4
foreach ($scores as $name => $score) {5
echo "$name: $score\n";6
}7
echo count($scores), "\n";Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Two key-value pairs. | scores = ["Ada" => 91, "Grace" => 88] | — | |
| A new key is appended. | 3 entries | — | |
| Each pass prints one pair, in insertion order. | 3 entries | Ada: 91 Grace: 88 Linus: 79 | |
| Print the number of entries. | 3 entries | Ada: 91 Grace: 88 Linus: 79 3 |
Cost and common mistakes
Lookup and insert are O(1) on average; the loop is O(n).
- Reading a missing key raises a warning and gives null; test with isset or array_key_exists first.
- Numeric-looking string keys such as "5" are converted to integer keys.
Try it yourself
Remove Grace before the loop.
Reveal answer and reasoning
Call unset($scores["Grace"]); the loop then prints two lines and count gives 2.