PHP Associative Arrays
In this page:
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
$user = ['email' => '[email protected]'];
echo $user['email'];
?>
Login to try C/C++/Java/PHP code in the editor
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
$person = ['name' => 'Aditi', 'age' => 24];
echo $person['name'] . " is " . $person['age'];
?>
Login to try C/C++/Java/PHP code in the editor
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
$profile = ['name' => 'Alice', 'age' => 30];
foreach ($profile as $key => $value) {
echo "$key: $value\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
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
$person = ['name' => 'Alice'];
if (isset($person['middleName'])) {
echo $person['middleName'];
} else {
echo "No middle name set.";
}
?>
Login to try C/C++/Java/PHP code in the editor
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
$row = ['id' => 1, 'name' => 'Alice', 'email' => '[email protected]'];
echo $row['name'];
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: