If we are traversing an array and need to update an element in some condition then it is quite tricky to do that in foreach loop.
For example, if we need to increase each element by 2 of an integer array then we can do that using for loop in this way:
$count = count($my_array);
for ($i = 0; $i < $count; $i++) {
$my_array[$i] += 2;
}
But it is not possible to do this in foreach loop:
foreach ($my_array as $data) {
$data += 2;
}
because in this way foreach is being used "by-value" so we can not update original element.
To do that we have to use foreach loop in this way:
foreach ($my_array as &$data) {
$data += 2;
}
or
foreach ($my_array as $key=>$val) {
$my_array[$key] += 2;
}
Hope this will help someone.
0 Comment(s)