๐ŸŽ“ A1Learner
๐Ÿ”

PHP Associative Arrays

An associative array is an array that stores each value under a name called a key. A pair joins one key to one value with the => sign.

Pairs with names as keys

Each pair joins a name to an age with the => sign. print_r shows each key beside its value.

<?php
$ages = ["Ana" => 30, "Bo" => 25];
print_r($ages);

Reading one value by its key

Square brackets hold the key. The printed value is the age stored under Ana.

<?php
$ages = ["Ana" => 30, "Bo" => 25];
echo $ages["Ana"] . "\n";

Changing a value by its key

The key Bo gets a new value. Reading by that key shows the new value.

<?php
$ages = ["Ana" => 30, "Bo" => 25];
$ages["Bo"] = 26;
echo $ages["Bo"] . "\n";

Printing each pair with foreach

Foreach puts the key in $name and the value in $age. Each round prints one line.

<?php
$ages = ["Ana" => 30, "Bo" => 25];
foreach ($ages as $name => $age) {
  echo $name . " is " . $age . "\n";
}

Example

<?php
$prices = ["Pen" => 2, "Book" => 8, "Bag" => 15];
foreach ($prices as $item => $price) {
  echo $item . " costs " . $price . "\n";
}

Key points

  • A key is a name or a number that labels one value.
  • Each key appears only once in an array.
  • The pairs keep the order in which they were added.
  • An associative array is a list of pairs, and each pair ties a value to its key.
  • Square brackets with a key inside read the value under that key.
  • Square brackets with a key and a new value change that pair.

In this example, the prices array holds three pairs. Each pair ties an item name to its price. Foreach prints one line per pair, in the order the pairs were added.

Note

A string key that holds a whole number, like "30", is stored as the number 30.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz PHP Compiler

Exercise

How does a program read the value stored under the key "Ana" in the $ages array?