The =>
operator assigns the keys of the array to the variable on the left hand side, and the value to the variable on the right hand side. For example, if you array is
$array = array(key1 => value1, key2 => value2, key3=> value3);
then
foreach ($array as $key => $value) {
echo "$key: $value\n";
}
will print
key1: value1
key2: value2
key3: value3
It is particularly useful if your array keys also have a meaning and you need them inside the for
-loop, separate from the values.
For example:
$students_by_id = array( 1234 => "John Smith", 2372 => "Pete Johnson" );
$grades = array( 1234 => 87, 2372 => 68 );
foreach( $grades as $student_id => $grade ) {
echo $students_by_id[$student_id] . " scored " . $grade . " / 100 points.\n";
}
Note that if the array is "not associative", e.g.
$array = array( value1, value2, value3 );
then PHP will create numeric indexes for you, and the $key
variable in
foreach ($array as $key => $value )
will run through 0, 1, 2, 3, ..., making your loop effectively equivalent to
for ($key = 0, $key < count($array); ++$key) {
$value = $array[$key];
// ...
}
In general I would still recommend the =>
notation, if not for efficiency then at least in case indices go missing from the list or you decide to switch to an associative array after all.