Associative Arrays
Associative arrays use named keys instead of numeric indexes.
Syntax
$ages = ["Peter" => 35, "Ben" => 37];An associative array uses named keys that you assign yourself, which makes the data more readable.
Each element is a key => value pair.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Store a user profile with named fields like 'name', 'email', and 'role' in an associative array.
- Map HTTP status codes to their descriptions in an associative array for a custom error handler.
- Build a settings array with string keys and look up individual options by name.
More examples
Defining an associative array
Associative arrays use string keys to name each value, making code self-documenting compared to numeric indexes.
<?php
$user = [
'name' => 'Alice',
'email' => '[email protected]',
'role' => 'admin',
];
echo $user['name']; // Alice
echo $user['role']; // adminAdding, updating and removing keys
Keys are created or updated with assignment and removed with unset() — all O(1) operations on the internal hash table.
<?php
$config = ['debug' => false, 'timezone' => 'UTC'];
$config['version'] = '1.0'; // add
$config['debug'] = true; // update
unset($config['timezone']); // remove
print_r($config);Iterating with foreach key => value
foreach with the key => value form exposes both sides of each pair, the standard way to iterate associative arrays.
<?php
$http = [
200 => 'OK',
404 => 'Not Found',
500 => 'Internal Server Error',
];
foreach ($http as $code => $message) {
echo "$code: $message\n";
}
Discussion