All lessons

Associative Arrays

8 min · PHP

Store values under named keys instead of numbered positions.

PHP · Associative Arrays0/5 cleared

Enemy 1 of 5

Keys instead of positions

An indexed array is great when order and position matter, but sometimes you want to look values up by a meaningful name instead of remembering "the score is at index 1." An associative array solves that by letting you choose your own keys instead of relying on automatic numbering.

You write one with the => arrow between each key and its value: ["name" => "Ada", "score" => 10]. Despite the different-looking syntax, it's still exactly the same array type in PHP as the indexed arrays from the previous lesson — PHP arrays are secretly always associative under the hood, and plain ["a", "b"] is just shorthand for [0 => "a", 1 => "b"]. Understanding that unifies the two lessons: everything you learned about count() and appending still applies here.

You look a value up the same way as before — square brackets — but using the key instead of a numeric index: $player["name"] rather than $player[0]. This tends to make code far more self-explanatory, since $player["score"] tells a reader what the value represents without them needing to remember an arbitrary position.

You
Kernel Hellhound

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: Ada