Associative Arrays
In summary, descriptive keys $e[“example”]; instead of numbers $e[0];
Associative arrays let you label your data with meaningful names instead of relying on numeric positions. Instead of remembering that $car[0] is the brand and $car[1] is the model, you use $car["brand"] and $car["model"]. This makes your code self-documenting and much easier to read.
Creating and Accessing Values
You create associative arrays using the => arrow syntax: "key" => "value". The key goes on the left, the value on the right. To access a value, you use the key name in square brackets: $car["model"] gives you “Mustang”.
Changing Values
Just like indexed arrays, you can change values by referencing the key: $car["year"] = 2024 updates the year. The syntax is identical to accessing — you're just assigning a new value instead of reading one.
Looping Through Associative Arrays
Here's where things get interesting. When you loop through an associative array with foreach, you can access both the key and the value using this syntax: foreach ($car as $key => $value). The arrow => separates them. On each loop, $key holds the key name (like “brand”) and $value holds the actual data (like “Ford”).
If you only care about the values and not the keys, you can still use the simple foreach ($car as $value) syntax you already know.
This is the structure you'll see everywhere in WordPress. User data? Associative array with keys like 'user_email', 'user_login', 'ID'. Post metadata? Associative arrays. Plugin settings? Associative arrays. Query arguments? You guessed it — associative arrays.