Difference between "as $key => $value" and "as $value" in PHP foreach
Let's say you have an associative array like this:
$a = array(
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => array('x'=>123)
);
In the first iteration : $key="one"
and $value=1
.
Sometimes you need this key ,if you want only the value , you can avoid using it.
In the last iteration : $key='seventeen'
and $value = array('x'=>123)
so to get value of the first element in this array
value, you need a key
, x in this case: $value['x'] =123
.
A very important place where it is REQUIRED to use the key => value
pair in foreach
loop is to be mentioned. Suppose you would want to add a new/sub-element to an existing item (in another key) in the $features
array. You should do the following:
foreach($features as $key => $feature) {
$features[$key]['new_key'] = 'new value';
}
Instead of this:
foreach($features as $feature) {
$feature['new_key'] = 'new value';
}
The big difference here is that, in the first case you are accessing the array's sub-value via the main array itself with a key to the element which is currently being pointed to by the array pointer.
While in the second (which doesn't work for this purpose) you are assigning the sub-value in the array to a temporary variable $feature
which is unset after each loop iteration.
Well, the $key => $value
in the foreach loop refers to the key-value pairs in associative arrays, where the key serves as the index to determine the value instead of a number like 0,1,2,... In PHP, associative arrays look like this:
$featured = array('key1' => 'value1', 'key2' => 'value2', etc.);
In the PHP code: $featured
is the associative array being looped through, and as $key => $value
means that each time the loop runs and selects a key-value pair from the array, it stores the key in the local $key
variable to use inside the loop block and the value in the local $value
variable. So for our example array above, the foreach loop would reach the first key-value pair, and if you specified as $key => $value
, it would store 'key1'
in the $key
variable and 'value1'
in the $value
variable.
Since you don't use the $key
variable inside your loop block, adding it or removing it doesn't change the output of the loop, but it's best to include the key-value pair to show that it's an associative array.
Also note that the as $key => $value
designation is arbitrary. You could replace that with as $foo => $bar
and it would work fine as long as you changed the variable references inside the loop block to the new variables, $foo
and $bar
. But making them $key
and $value
helps to keep track of what they mean.