TExcelTAD
Home › PHP › PHP Associative Arrays

PHP Associative Arrays

An associative array uses keys that you choose — usually strings — instead of automatic numbers. It is PHP's version of a dictionary or map, and it is everywhere: form data, configuration, database rows and decoded JSON all arrive as associative arrays.

Creating one

Write each pair as key => value:

php · try it yourself
<?php
$book = [
    'title'  => 'The Quiet Compiler',
    'author' => 'L. Tran',
    'pages'  => 312,
];

echo $book['title'] . ' by ' . $book['author'] . PHP_EOL;
echo "It has {$book['pages']} pages." . PHP_EOL;

$book['pages'] = 320;       // change a value
$book['year'] = 2024;       // add a new pair
echo count($book) . ' fields' . PHP_EOL;
The Quiet Compiler by L. Tran
It has 312 pages.
4 fields

The echo lines run before the change, so they still see 312 pages. Values are replaced in place, while a new key is appended at the end.

Tip: Inside double quotes, wrap an array element in curly braces — "{$book['pages']}" — so PHP knows where the expression ends.

Looping over keys and values

foreach ($array as $key => $value) gives you both parts of each pair, in insertion order.

php · try it yourself
<?php
$stock = ['apples' => 12, 'pears' => 0, 'plums' => 7];

foreach ($stock as $fruit => $count) {
    $status = $count > 0 ? "$count left" : 'sold out';
    echo str_pad($fruit, 8) . $status . PHP_EOL;
}

echo 'Fruits: ' . implode(', ', array_keys($stock)) . PHP_EOL;
echo 'Total: ' . array_sum($stock) . PHP_EOL;
apples  12 left
pears   sold out
plums   7 left
Fruits: apples, pears, plums
Total: 19

Does a key exist?

There are two common checks, and they differ in one detail: how they treat null.

Check Key missing Key exists, value null Key exists, other value
isset($a['k']) false false true
array_key_exists('k', $a) false true true
$a['k'] ?? 'default' 'default' 'default' the value
php · try it yourself
<?php
$user = ['name' => 'Kim', 'phone' => null];

var_dump(isset($user['phone']));
var_dump(array_key_exists('phone', $user));
echo ($user['email'] ?? 'no email') . PHP_EOL;
echo 'Name: ' . ($user['name'] ?? 'guest') . PHP_EOL;
bool(false)
bool(true)
no email
Name: Kim

Most of the time ?? is all you need: it reads the key if it is set and falls back to a default otherwise — without any warning.

Keys are normalised

PHP quietly converts some keys:

  • A string that looks like a whole decimal number ("8") becomes the integer 8.
  • true/false become 1/0, and null becomes "".
  • Floats are truncated to integers (1.7 → 1, and this triggers a deprecation notice).

So $a["8"] and $a[8] are the same element. Stick to plain strings and integers to avoid surprises.

Handy functions for associative arrays

php · try it yourself
<?php
$prices = ['tea' => 2.5, 'cake' => 4.0, 'juice' => 3.0];

print_r(array_keys($prices));
print_r(array_flip(['red' => 'r', 'green' => 'g']));

$defaults = ['theme' => 'light', 'lang' => 'en'];
$chosen = ['lang' => 'vi'];
print_r(array_merge($defaults, $chosen));
print_r($chosen + $defaults);
Array
(
    [0] => tea
    [1] => cake
    [2] => juice
)
Array
(
    [r] => red
    [g] => green
)
Array
(
    [theme] => light
    [lang] => vi
)
Array
(
    [lang] => vi
    [theme] => light
)

array_merge() lets later arrays overwrite earlier string keys; the + operator keeps the left value when a key appears in both. Both are common ways to apply defaults.

Function Purpose
array_keys($a) / array_values($a) just the keys / just the values
array_flip($a) swap keys and values
array_merge($a, $b) combine, right side wins
$a + $b combine, left side wins
array_key_first($a) / array_key_last($a) first / last key

Test yourself

Given $a = ['x' => null];, what does isset($a['x']) return?

  1. true
  2. false
  3. null
  4. It throws an error

What is the result of ['a' => 1] + ['a' => 2, 'b' => 3]?

  1. ['a' => 2, 'b' => 3]
  2. ['a' => 1, 'b' => 3]
  3. ['a' => 3]
  4. [1, 2, 3]

Which loop header gives you both key and value?

  1. foreach ($a as $v)
  2. foreach ($a => $k as $v)
  3. foreach ($a as $k => $v)
  4. for ($k => $v in $a)