PHP Associative Arrays
Map names to values and loop over keys and values.
On this page
PHP arrays.
- Map names to values and loop over keys and values.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
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.
Code example
<?php
$scores = ["Ada" => 91, "Grace" => 88];
$scores["Linus"] = 79;
foreach ($scores as $name => $score) {
echo "$name: $score\n";
}
echo count($scores), "\n";Ada: 91 Grace: 88 Linus: 79 3
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
<?php$scores = ["Ada" => 91, "Grace" => 88];$scores["Linus"] = 79;foreach ($scores as $name => $score) { echo "$name: $score\n";}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 |
Behind the scenes
How PHP processes this code
The PHP runtime executes the script. echo writes to the response or terminal output.
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.