An associative array uses names (keys) instead of numbers to find items. It works like a record with labelled fields, such as a user profile.
<?php
$user = [
"name" => "Isha",
"email" => "isha@example.com",
"age" => 29,
];
echo $user["name"] . " - " . $user["email"];
Isha - isha@example.com
The => arrow connects a key to its value. Keys are usually strings, and each key appears only once.
Add and change items
<?php
$user = ["name" => "Isha"];
$user["city"] = "Kochi"; // new key
$user["name"] = "Isha R."; // change existing
print_r($user);
Array
(
[name] => Isha R.
[city] => Kochi
)
Check whether a key exists
<?php
$user = ["name" => "Isha", "phone" => null];
var_dump(isset($user["name"]));
var_dump(isset($user["phone"])); // false: the value is null
var_dump(array_key_exists("phone", $user)); // true: the key exists
var_dump(isset($user["email"]));
bool(true)
bool(false)
bool(true)
bool(false)
isset() says false for a key whose value is null. array_key_exists() only checks the key. Pick the one that matches your question.
Defaults for missing keys
<?php
$user = ["name" => "Isha"];
$role = $user["role"] ?? "guest";
echo $role;
guest
Loop through keys and values
<?php
$stock = ["pens" => 40, "books" => 12, "bags" => 5];
foreach ($stock as $item => $quantity) {
echo "$item: $quantity\n";
}
pens: 40
books: 12
bags: 5
Keys and values separately
<?php
$stock = ["pens" => 40, "books" => 12];
print_r(array_keys($stock));
print_r(array_values($stock));
Array
(
[0] => pens
[1] => books
)
Array
(
[0] => 40
[1] => 12
)
Remove a key
<?php
$user = ["name" => "Isha", "password" => "secret"];
unset($user["password"]);
echo count($user);
1
Mixing numeric and string keys
PHP allows it, but avoid it. An array is easier to understand when it is either a list or a record.
Where you see this
- Rows from a database.
- Decoded JSON objects.
- Form data (
$_POSTis an associative array). - Settings and configuration.
Name keys in one style
snake_case or camelCase for keys and stay with it. A typo in a key gives null or a warning, not a clear error.