PHP ยท Chapter 21 of 44

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.

Syntax
$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.

Example 1 (php)
<?php
  $person = ["name" => "Amy", "age" => 25];
  echo $person["name"] . " is " . $person["age"];
?>
Output
Amy is 25

Values are accessed using their string keys instead of numeric positions.

Example 2 (php)
<?php
  $ages = ["Amy" => 25, "Ben" => 30];
  foreach ($ages as $name => $age) {
    echo "$name: $age ";
  }
?>
Output
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.
๐Ÿ’ก Note: Associative array keys should be unique โ€” assigning to an existing key overwrites its previous value.

๐Ÿ“ Quick Quiz

1. Which operator associates a key with a value in an array?

2. How do you access both key and value in a foreach loop?

3. What happens if you assign a value to an existing key?