Skip to content

PHP Tutorial Arrays

Associative Arrays

Lesson 119 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

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.

index.php
PHP
<?php
$user = [
    "name" => "Isha",
    "email" => "isha@example.com",
    "age" => 29,
];

echo $user["name"] . " - " . $user["email"];
Output
OUTPUT
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

index.php
PHP
<?php
$user = ["name" => "Isha"];

$user["city"] = "Kochi";    // new key
$user["name"] = "Isha R.";  // change existing

print_r($user);
Output
OUTPUT
Array
(
    [name] => Isha R.
    [city] => Kochi
)

Check whether a key exists

index.php
PHP
<?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"]));
Output
OUTPUT
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

index.php
PHP
<?php
$user = ["name" => "Isha"];

$role = $user["role"] ?? "guest";

echo $role;
Output
OUTPUT
guest

Loop through keys and values

index.php
PHP
<?php
$stock = ["pens" => 40, "books" => 12, "bags" => 5];

foreach ($stock as $item => $quantity) {
    echo "$item: $quantity\n";
}
Output
OUTPUT
pens: 40
books: 12
bags: 5

Keys and values separately

index.php
PHP
<?php
$stock = ["pens" => 40, "books" => 12];

print_r(array_keys($stock));
print_r(array_values($stock));
Output
OUTPUT
Array
(
    [0] => pens
    [1] => books
)
Array
(
    [0] => 40
    [1] => 12
)

Remove a key

index.php
PHP
<?php
$user = ["name" => "Isha", "password" => "secret"];

unset($user["password"]);

echo count($user);
Output
OUTPUT
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 ($_POST is an associative array).
  • Settings and configuration.
lightbulb
Name keys in one style
Pick snake_case or camelCase for keys and stay with it. A typo in a key gives null or a warning, not a clear error.