PHP Associative Arrays
An associative array uses named keys that you assign to each value, instead of relying on sequential numeric indexes. This makes it easy to store related data, like a person's attributes, in a single structure.
You can create associative arrays with the => operator, and loop through them using foreach with both key and value variables to access each key-value pair.
$arr = ["key1" => "value1", "key2" => "value2"];Creating associative arrays
Keys are written before the => arrow, followed by the corresponding value, such as ["name" => "Amy", "age" => 25].
Looping with keys and values
foreach ($array as $key => $value) lets you access both the key and value for each pair while iterating over an associative array.
<?php
$person = ["name" => "Amy", "age" => 25];
echo $person["name"] . " is " . $person["age"];
?>Amy is 25Values are accessed using their string keys instead of numeric positions.
<?php
$ages = ["Amy" => 25, "Ben" => 30];
foreach ($ages as $name => $age) {
echo "$name: $age ";
}
?>Amy: 25 Ben: 30 foreach with key => value gives you access to both parts of each pair.
Key points
- Associative arrays use named string keys instead of numeric indexes.
- The => arrow associates a key with its value.
- foreach with $key => $value loops through both keys and values.
- Associative arrays are ideal for representing structured records.
