Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change initial array inside the foreach loop?

Tags:

php

i want to have a foreach loop where the initial array is changed inside the loop.

eg.

$array = array('red', 'blue');
foreach($array as $key => $value) {
    $array[] = 'white';
    echo $value . '<br />';
}

in this loop the loop will print out red and blue although i add another element inside the loop.

is there any way to change the initial array inside the loop so new elements will be added and the foreach will use the new array whatever is changed?

i need this kind of logic for a specific task:

i will have a if statement that search for a link. if that link exists, it is added to the array. the link content will be fetched to be examined if it contains another link. if so, this link is added, and the content will be fetched, so on so forth.. when no link is further founded, the foreach loop will exit

like image 618
ajsie Avatar asked Feb 27 '10 16:02

ajsie


People also ask

Can you modify array in forEach?

To change the value of all elements in an array: Use the forEach() method to iterate over the array. The method takes a function that gets invoked with the array element, its index and the array itself. Use the index of the current iteration to change the corresponding array element.

Does forEach change the original array?

forEach() does not mutate the array on which it is called.

Can you change a foreach loop?

Why C#'s foreach loop cannot change what it loops over. With a foreach loop we easily iterate over all elements in a collection. During each pass through the loop, the loop variable is set to an element from a collection.

Can we use forEach inside for loop?

This foreach is itself inside the main loop, and echoing out a div for each ID has access to. In the life cycle of the main array, this will happen 13 times. The reason you are seeing duplicates is because you have top-level array elements which contain the same IDs as other elements.


5 Answers

I don't think this is possible with a foreach loop, at least the way you wrote it : doesn't seem to just be the way foreach works ; quoting the manual page of foreach :

Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself.


Edit : after thinking a bit about that note, it is actually possible, and here's the solution :

The note says "Unless the array is referenced" ; which means this portion of code should work :

$i = 0;
$array = array('red', 'blue');
foreach($array as $key => & $value) {
    $array[] = 'white';
    echo $value . '<br />';
    if ($i++ >= 5) {
        break;   // security measure to ensure non-endless loop
    }
}

Note the & before $value.

And it actually displays :

red
blue
white
white
white
white

Which means adding that & is actually the solution you were looking for, to modify the array from inside the foreach loop ;-)


Edit : and here is the solution I proposed before thinking about that note :

You could do that using a while loop, doing a bit more work "by hand" ; for instance :

$i = 0;

$array = array('red', 'blue');

$value = reset($array);
while ($value) {
    $array[] = 'white';
    echo $value . '<br />';
    if ($i++ >= 5) {
        break;   // security measure to ensure non-endless loop
    }
    $value = next($array);
}

Will get you this output :

red
blue
white
white
white
white
like image 73
Pascal MARTIN Avatar answered Sep 25 '22 09:09

Pascal MARTIN


What you need to do is move the assignment inside the for loop and check the length of the array every iteration.

$array = array('red', 'blue');
for($i = 0; $i < count($array); $i++)
{
   $value = $array[$i];
   array_push($array, 'white');
   echo $value . '<br />';
}

Be careful, this will cause an infinite loop (white will be added to the end of the array at every loop).

like image 40
MrValdez Avatar answered Sep 25 '22 09:09

MrValdez


Maybe you should use some other way, like:

$ar = array('blue', 'red');
while ($a = array_pop($ar) {
     array_push($ar, 'white');
}

Or something like this...

like image 32
Enrico Carlesso Avatar answered Sep 25 '22 09:09

Enrico Carlesso


You can access the array by using the $key

$array = array('red', 'blue');
foreach($array as $key => $value) {
    $array[$key] = 'white';
}
like image 40
freelivenet Avatar answered Sep 23 '22 09:09

freelivenet


In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference. [source]

All you have to do to your old code is

precede $value with &

like so

$array = array('red', 'blue');
foreach($array as $key => &$value) {// <-- here
    $array[] = 'white';
    echo $value . '<br />';
}

A while loop would be a better solution.

while (list ($key, $value) = each ($array) ) {
    $array[] = 'white';
    echo $value . '<br />';
}

If you don't need the $key variable, as your example suggests then using $value = array_pop($array) instead if list ($key, $value) = each ($array) would be a less expensive option. see @enrico-carlesso's Answer Here

As your array is sequantial(numeric,indexed) and not associative then you could use a for loop instead.

for ($key = 0; $key < count($array); ++$key) {
    $value = $array[$i];

    $array[] = 'white';
    echo $value . '<br />';
}

As a side note.

I don't understand why its &$value and not &array.

&$value would suggest you can only modify the current element within the loop. &array would suggest you could modify all array elements within the loop, including adding/removing element.

like image 45
TarranJones Avatar answered Sep 25 '22 09:09

TarranJones