Keys in the Foreach Loop in PHP
In the foreach loop, you can get not
only the elements of the iterated array, but
also the keys. In this case, after as, you should
specify the following construct: $key => $elem.
The variable $key will store
the keys, and the variable $elem will store the corresponding
elements for these keys.
To see in practice how to work with keys, let's do the following - on each iteration of the loop, we will display the array key and its corresponding element separated by a hyphen:
<?php
$arr = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5];
foreach ($arr as $key => $elem) {
echo $key . '-' . $elem;
}
?>
Given an array:
<?php
$arr = ['user1' => 30, 'user2' => 32, 'user3' => 33];
?>
Using a foreach loop, display the
user names and their corresponding ages.