1

I have an array:

$colors = array("red", "green");

I am using this array in foreach and I want to update this array inner the foreach for example like this:

foreach( $colors as $color ){
    if( $color=='green' ){
        array_push($colors, 'blue');  //now $colors is ["red", "green", "blue"]
    }
    echo $color . "<br>";
}

Result is:

red
green

and blue is not echo in result!

How I can update foreach variable inner it?


update: I do this with for and it is work.

$colors = array("red", "green");

for( $i=0; $i < count($colors); $i++ ){
    if( $colors[$i]=='green' ){
        array_push($colors, 'blue'); //now $colors is ["red", "green", "blue"]
    }
    echo $colors[$i]."<br>";
}

result is

red
green
blue

How I can do this with foreach?

Saeed sdns
  • 804
  • 7
  • 17
  • 1
    https://stackoverflow.com/questions/10057671/how-does-php-foreach-actually-work may be worth a read to see how `foreach` works. – Nigel Ren May 08 '20 at 13:55

2 Answers2

3

If you pass as reference (https://www.php.net/manual/en/language.references.php) (see &$color) it will work as it will point to the same memory address, thus updating the $colors var:

<?php
$colors = array("red", "green");
foreach( $colors as &$color ){
    if( $color=='green' ){
        array_push($colors, 'blue');
    }
    echo $color . "<br>";
}

Of course there is no need for this if you print $colors outside the loop, with print_r($colors);. This pass by reference is only needed inside the loop.

Felippe Duarte
  • 14,901
  • 2
  • 25
  • 29
-1
foreach($colors as $color){
   if( $color=='green' ){
      $colors[]= 'blue';  //now $colors is ["red", "green", "blue"]
   }
}

Now use foreach loop to print all values under $color variable

foreach($colors as $color){
   echo $color."\n";
}
Feroz
  • 143
  • 8