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
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 wayforeach
works ; quoting the manual page offoreach
: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 :
Note the
&
before$value
.And it actually displays :
Which means adding that
&
is actually the solution you were looking for, to modify the array from inside theforeach
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 :Will get you this output :