Saeed sdns
Saeed sdns

Reputation: 970

php - update foreach variable inner it

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?

Upvotes: 1

Views: 40

Answers (2)

Feroz
Feroz

Reputation: 153

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";
}

Upvotes: -1

Felippe Duarte
Felippe Duarte

Reputation: 15131

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.

Upvotes: 3

Related Questions