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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I had forgotten that it behaved that way with the reference.
-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";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.