HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to PHPVariablesData TypesOperatorsStringsArraysAssociative ArraysConditions (if / else)Loops (for / foreach / while)Functions
REFERENCE
📖 Overview
🖥️ Output
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Array
🔁 Condition & Loop
🧩 Function
🔄 Type & Conversion
PHP›Associative Arrays

Associative Arrays

Storing and traversing structured data using key=>value mappings.

Simple enough for a 5-year-old to understand

Key => value

You use your own keys instead of numeric indices (with =>). It's like a dictionary.

Example code
1
<?php
Start.
DefinitionStart.
2
$person = ["name" => "Alex", "age" => 36];
Keyed array.
DataKeyed array.
3
echo $person["name"];
Access with key: Alex
Output / InputAccess with key: Alex
DefinitionDataOutput / Input
💡 Hint: An associative array is ideal for holding fields of a record (user, product).

About this topic

An associative array is an array where you access elements using meaningful keys instead of numbers. In PHP, it's not a separate type — it's the same array structure used with string keys.

You will encounter this structure everywhere in PHP: form data, session data, database result rows, and JSON parsing. A database row is naturally an associative array — column names are keys, and cell values are values.

The important thing to watch out for is whether a key exists. Reading a non-existent key generates a warning in PHP 8; for external data, you should always use null coalescing or array_key_exists.

What you will learn

  • Creating an array with string keys
  • Reading and writing values using keys
  • Iterating over both keys and values together with foreach
  • Using array_keys and array_values
  • The difference between isset and array_key_exists
  • Working with multidimensional arrays

When to use?

Configuration data, API responses, and database rows are processed as associative arrays. json_decode returns an object by default; if you pass true as the second parameter, you get an associative array, which is usually more practical.

When you need to carry multiple related values together, an associative array is a quick solution; however, if the structure is fixed and repetitive, using a class is safer because it prevents typos.

Common mistakes

Wrong

$user = ["name" => "Ada", "age" => 36];
echo $user["eposta"];

Reading a non-existent key gives a "Warning: Undefined array key" warning and returns null. The most common error with associative arrays is a key typo, and PHP cannot catch this at compile time.

Correct

$user = ["name" => "Ada", "age" => 36];
echo $user["eposta"] ?? "-";

Wrong

$config = ["debug" => null];
if (isset($config["debug"])) {
    echo "setting exists";
}

isset returns FALSE when the value is null — even though the key exists. To distinguish the existence of a key from a null value, array_key_exists should be used.

Correct

$config = ["debug" => null];
if (array_key_exists("debug", $config)) {
    echo "setting exists";
}

Wrong

$user = ["name" => "Ada"];
foreach ($user as $value) {
    echo $value;
}

A single-variable foreach only gives you the VALUES; you lose the key. In an associative array, you usually need the key as well, so the two-variable syntax should be used.

Correct

$user = ["name" => "Ada"];
foreach ($user as $key => $value) {
    echo "$key: $value";
}

Frequently asked questions

What is the difference between isset and array_key_exists?

isset returns false if the key does not exist OR its value is null. array_key_exists only checks for the existence of the key. This distinction matters when a null value is meaningful — such as a setting being intentionally left blank.

How do I sort an associative array?

Use asort to sort by value and ksort to sort by key. Regular sort LOSES the keys and converts them to numeric indices — using this on an associative array will corrupt the data. This is a common mistake.

Should I use an array or a class?

If the structure is fixed and passed around in many places in the code, use a class. With an array, a key typo isn't visible until runtime; with a class, IDEs and tools will warn you immediately if a property name is misspelled. For temporary and flexible data, an array is enough.

Summary

An associative array is a PHP array with string keys and is the natural format for form, API, and database data. Non-existent keys produce a warning, isset ignores null values, and asort or ksort should be used for sorting.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code