← Back to PHP Course | Chapter 7: Arrays | Lesson 8 of 13

PHP Associative Arrays

What are Associative Arrays?

An associative array uses strings (or any scalar value) as keys instead of automatic integers, letting you store data as labeled fields — like $user[email] — which reads far more clearly than a numbered index would.

Example: What are Associative Arrays?

php
<?php
$user = ['email' => '[email protected]'];
echo $user['email'];
?>

Accessing and Modifying Elements

You define one with [name => Aditi, age => 24], where => separates each key from its value, and this is the closest PHP equivalent to what other languages call a dictionary, hash map, or object literal.

Example: Accessing and Modifying Elements

php
<?php
$person = ['name' => 'Aditi', 'age' => 24];
echo $person['name'] . " is " . $person['age'];
?>

Adding New Key-Value Pairs

foreach ($array as $key => $value) lets you loop over both the label and the data at once, which is the standard way to print out or process every field in an associative array such as a user's profile.

Example: Adding New Key-Value Pairs

php
<?php
$profile = ['name' => 'Alice', 'age' => 30];
foreach ($profile as $key => $value) {
    echo "$key: $value\n";
}
?>

Looping Through Associative Arrays

isset($array[key]) checks whether a given key exists before you try to read it, protecting against PHP notices when optional fields — like a middle name — might be missing from the array.

Example: Looping Through Associative Arrays

php
<?php
$person = ['name' => 'Alice'];
if (isset($person['middleName'])) {
    echo $person['middleName'];
} else {
    echo "No middle name set.";
}
?>

Checking If a Key Exists

Associative arrays are the natural fit for representing a single structured record, such as one row from a database query, where each key names a specific column and its value.

Example: Checking If a Key Exists

php
<?php
$row = ['id' => 1, 'name' => 'Alice', 'email' => '[email protected]'];
echo $row['name'];
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.