How to Loop Through an Associative Array in PHP
Iterating over an associative array is a fundamental task in PHP
development, allowing you to access both the keys and their
corresponding values. This article provides a straightforward guide on
how to use the foreach loop to traverse associative arrays,
complete with code examples demonstrating how to retrieve keys, values,
or both.
In PHP, an associative array uses named keys that you assign to
values. The most efficient and readable way to loop through these
key-value pairs is by using the foreach loop.
Accessing Both Keys and Values
To access both the key and the value of each element in the array,
you use the $key => $value syntax within the
foreach statement.
<?php
$user = [
"name" => "Alex",
"email" => "alex@example.com",
"role" => "Developer"
];
foreach ($user as $key => $value) {
echo "Key: " . $key . ", Value: " . $value . "\n";
}
?>Output:
Key: name, Value: Alex
Key: email, Value: alex@example.com
Key: role, Value: Developer
Accessing Only Values
If you do not need the keys and only want to work with the values,
you can omit the $key => portion of the loop.
<?php
$user = [
"name" => "Alex",
"email" => "alex@example.com",
"role" => "Developer"
];
foreach ($user as $value) {
echo "Value: " . $value . "\n";
}
?>Output:
Value: Alex
Value: alex@example.com
Value: Developer
Modifying Values During the Loop
By default, foreach works on a copy of the array. If you
need to modify the array values directly during the iteration, you can
pass the value by reference using the ampersand (&)
symbol.
<?php
$prices = [
"item1" => 10,
"item2" => 20,
];
foreach ($prices as $key => &$value) {
$value = $value * 1.1; // Increase price by 10%
}
unset($value); // It is good practice to break the reference after the loop
print_r($prices);
?>Using the foreach loop is the standard and most readable
method for handling associative arrays in PHP, making code maintenance
and data manipulation simple and clean.