Associative Arrays

JA JASWANT Updated 30 Oct 2026
8 min read ·Lesson 198 of 209

What Is an Associative Array?

In simple terms: An associative array stores values under names (keys) instead of position numbers. Instead of "the second item", you ask for "the email" or "the price". Technically: An associative array is a PHP array whose keys are meaningful strings (or chosen integers) rather than automatic sequential indexes. It works like a dictionary or map: each key is unique and points to one value. Lookups by key are very fast, regardless of the array's size.

$user = [
    'name'  => 'Asha',
    'email' => 'asha@example.com',
    'city'  => 'Chennai',
];

Why Associative Arrays Are So Common

  • Records: a user, product, or order has named fields.
  • Settings: configuration options by name.
  • Lookups: country codes to names, status codes to labels.
  • Counting and grouping: words to counts, categories to products.
  • Data from outside: database rows (fetch(PDO::FETCH_ASSOC)), form data ($_POST), and decoded JSON objects all arrive as associative arrays.

Creating Associative Arrays

Syntax

$array = [
    'key1' => value1,
    'key2' => value2,
];

The => operator ("double arrow") assigns a value to a key.

Example

<?php
$product = [
    'sku' => 'LAMP-01',
    'name' => 'Desk Lamp',
    'price' => 1299,
    'inStock' => true,
];
print_r($product);

Output

Array
(
    [sku] => LAMP-01
    [name] => Desk Lamp
    [price] => 1299
    [inStock] => 1
)

print_r() shows true as 1; use var_dump() when you need to see exact types.


Accessing Values

<?php
$user = ['name' => 'Asha', 'email' => 'asha@example.com', 'city' => 'Chennai'];
echo $user['name'] . "\n";
echo "Lives in {$user['city']}\n";

Output

Asha
Lives in Chennai

In double-quoted strings, use curly braces ({$user['city']}) to access elements with quoted keys (see String Interpolation).

Missing Keys

<?php
$user = ['name' => 'Asha', 'email' => 'asha@example.com'];
echo $user['phone'];

Output

PHP Warning:  Undefined array key "phone" in /path/script.php on line 4

Reading a key that does not exist raises a warning and returns null. Optional keys should be read safely:

<?php
$user = ['name' => 'Asha', 'email' => 'asha@example.com'];
echo $user['phone'] ?? 'Phone not provided';
echo "\n";

Output

Phone not provided

isset() vs array_key_exists()

<?php
$profile = ['name' => 'Asha', 'nickname' => null];
var_dump(isset($profile['nickname']));
var_dump(array_key_exists('nickname', $profile));
var_dump(isset($profile['age']));

Output

bool(false)
bool(true)
bool(false)
  • isset() returns false for keys whose value is null.
  • array_key_exists() returns true whenever the key exists, even if its value is null. Use array_key_exists() when "set to null" and "not set at all" mean different things (for example, a user who explicitly cleared their nickname).

Adding, Updating, and Removing

<?php
$settings = ['theme' => 'light', 'language' => 'en'];
$settings['perPage'] = 25;        // add a new key
$settings['theme'] = 'dark';      // update an existing key
unset($settings['language']);     // remove a key
print_r($settings);

Output

Array
(
    [theme] => dark
    [perPage] => 25
)

Assigning to a key either creates it (if it does not exist) or replaces its value (if it does). Keys are unique — an array cannot contain the same key twice.


Looping Over Associative Arrays

<?php
$stock = ['Keyboard' => 12, 'Mouse' => 0, 'Monitor' => 4];
foreach ($stock as $product => $quantity) {
    $status = $quantity > 0 ? "$quantity available" : 'sold out';
    echo "$product: $status\n";
}
echo "Products: " . implode(', ', array_keys($stock)) . "\n";
echo "Total units: " . array_sum($stock) . "\n";

Output

Keyboard: 12 available
Mouse: sold out
Monitor: 4 available
Products: Keyboard, Mouse, Monitor
Total units: 16
  • foreach ($array as $key => $value) gives both the key and the value.
  • array_keys() returns the keys as a list; array_values() returns the values as a list.
  • Functions like array_sum() work on the values.

Key Rules

Insertion Order Is Preserved

Elements stay in the order they were added. Sorting functions change the order explicitly (see below).

Keys Are Case-Sensitive

<?php
$data = ['Name' => 'Asha', 'name' => 'Bala'];
echo count($data) . "\n";
echo $data['name'] . "\n";

Output

2
Bala

'Name' and 'name' are different keys. Normalize keys (for example, to lowercase) when they come from user input or external systems.

Integer-Like String Keys Become Integers

A string key that looks like a canonical integer, such as "42", is stored as the integer 42. "042" and "4.2" stay strings. This rarely matters, but explains why $array["42"] and $array[42] refer to the same element (see PHP Type Juggling).


Sorting Associative Arrays

Sorting functions for associative arrays keep each key with its value:

FunctionSorts ByOrder
asort()ValueAscending
arsort()ValueDescending
ksort()KeyAscending
krsort()KeyDescending
<?php
$prices = ['Mouse' => 799, 'Keyboard' => 1499, 'Cable' => 199];
asort($prices);
print_r($prices);
ksort($prices);
print_r($prices);

Output

Array
(
    [Cable] => 199
    [Mouse] => 799
    [Keyboard] => 1499
)
Array
(
    [Cable] => 199
    [Keyboard] => 1499
    [Mouse] => 799
)

sort() and rsort() would discard the keys and re-index the array from 0 — a common mistake with associative arrays. Sorting is covered in Sorting Arrays.


Associative Arrays as Lookup Tables

Because looking up a key is very fast, associative arrays are ideal for mapping codes to values:

<?php
$statusLabels = [
    'pending' => 'Awaiting payment',
    'paid' => 'Payment received',
    'shipped' => 'On the way',
    'delivered' => 'Delivered',
];
$orders = [['id' => 1, 'status' => 'shipped'], ['id' => 2, 'status' => 'refunded']];
foreach ($orders as $order) {
    $label = $statusLabels[$order['status']] ?? 'Unknown status';
    echo "Order {$order['id']}: $label\n";
}

Output

Order 1: On the way
Order 2: Unknown status

One array lookup replaces a chain of if statements, and ?? handles unknown codes.

Counting With an Associative Array

<?php
$votes = ['PHP', 'Python', 'PHP', 'Go', 'PHP', 'Python'];
$counts = [];
foreach ($votes as $language) {
    $counts[$language] = ($counts[$language] ?? 0) + 1;
}
arsort($counts);
print_r($counts);

Output

Array
(
    [PHP] => 3
    [Python] => 2
    [Go] => 1
)

Each language becomes a key the first time it appears (?? 0 supplies the starting count). PHP's array_count_values($votes) performs the same counting in one call.


Combining Defaults With Overrides

A common task is applying user settings on top of default settings:

<?php
$defaults = ['theme' => 'light', 'language' => 'en', 'perPage' => 20];
$userSettings = ['language' => 'ta', 'perPage' => 50];
print_r(array_replace($defaults, $userSettings));
print_r($userSettings + $defaults);

Output

Array
(
    [theme] => light
    [language] => ta
    [perPage] => 50
)
Array
(
    [language] => ta
    [perPage] => 50
    [theme] => light
)
  • array_replace($defaults, $overrides) keeps the order of the defaults and replaces values with matching keys.
  • $overrides + $defaults (the union operator) keeps the left array's values and adds missing keys from the right. Both produce the same settings; they differ only in key order. array_merge() behaves like array_replace() for string keys. See Merge Arrays.

Associative Arrays and JSON

JSON objects map directly to associative arrays:

<?php
$json = '{"id": 42, "name": "Asha", "address": {"city": "Madurai", "pin": "625001"}}';
$customer = json_decode($json, true);
echo $customer['name'] . ' — ' . $customer['address']['city'] . "\n";
$customer['verified'] = true;
echo json_encode($customer) . "\n";

Output

Asha — Madurai
{"id":42,"name":"Asha","address":{"city":"Madurai","pin":"625001"},"verified":true}

json_decode() with true produces nested associative arrays, which can be read and modified like any other array and encoded back to JSON.


Practical Example: Turning Parallel Lists Into a Record

<?php
$days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];
$sales = [12500, 9800, 15200, 11000, 18750];
$salesByDay = array_combine($days, $sales);
arsort($salesByDay);
$bestDay = array_key_first($salesByDay);
echo "Best day: $bestDay (₹" . number_format($salesByDay[$bestDay]) . ")\n";
echo "Weekly total: ₹" . number_format(array_sum($salesByDay)) . "\n";
foreach ($salesByDay as $day => $amount) {
    printf("%-3s %s\n", $day, str_repeat('█', intdiv($amount, 2500)));
}

Output

Best day: Fri (₹18,750)
Weekly total: ₹67,250
Fri ███████
Wed ██████
Mon █████
Thu ████
Tue ███

Step-by-Step Explanation

  1. array_combine($days, $sales) builds an associative array using the first array as keys and the second as values. Each day and its sales amount now stay together.
  2. arsort() sorts by sales, highest first, keeping the day names.
  3. array_key_first() returns the first key after sorting — the best day.
  4. A simple text bar chart uses one block per ₹2,500 (intdiv($amount, 2500)). With two separate lists, sorting the sales would have broken the link to the days. The associative array keeps the data consistent.

Common Mistakes

Reading Optional Keys Without a Default

Effect: "Undefined array key" warnings. Fix: Use ??, isset(), or array_key_exists().

Using sort() on Associative Arrays

Effect: Keys are lost and replaced with 0, 1, 2, …. Fix: Use asort(), arsort(), ksort(), or krsort().

Inconsistent Key Case or Spelling

Effect: 'Email' and 'email' become two different entries. Fix: Normalize keys and define them in one place (constants or a class).

Treating isset() as "Key Exists"

Effect: Keys with null values are reported as missing. Fix: Use array_key_exists() when the difference matters.

Large "Magic" Arrays Passed Everywhere

Effect: Typos in keys are not caught, and nobody knows which keys an array should contain. Fix: For important domain data, use classes with typed properties; keep associative arrays for simple data and lookups.


Best Practices

  • Use associative arrays for records, settings, lookups, and counting.
  • Read optional keys with ?? and choose isset() or array_key_exists() deliberately.
  • Use key-preserving sort functions (asort, arsort, ksort, krsort).
  • Combine related lists with array_combine() instead of keeping parallel arrays.
  • Keep key names consistent, and consider classes for complex, frequently used structures. Official reference: https://www.php.net/manual/en/language.types.array.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else User-defined Functions Slicing Strings Function Arguments PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where Debugging PHP Project: Image Upload Gallery $_SESSION $_ENV PHP RegEx RegEx Patterns Heredoc and Nowdoc RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures Composer PHP Form Handling PHP XML Parsers PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro PHP Class Constants Encryption with Sodium Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions
Ask about this post
AI Ask about this post

Ask questions about Associative Arrays and get answers drawn from it.

Signed-in readers only.