"change initial array inside the foreach loop?" Answer’s

0

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
Wednesday, March 31, 2021
 
lena
answered 11 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :