I have a database call and I\'m trying to figure out what the $key => $value
does in a foreach
loop.
The reason I ask is because both these
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.