How can I change my array, which directly affects

2020-04-21 08:25发布

问题:

I loop through an array, which I have, using a foreach loop. However within the foreach loop I need to modify the array, so that it directly affects my foreach loop.

So I will make an example of my problem:

<?php

    $array = ["Red", "Yellow", "Blue", "Orange"];

    foreach($array as $color) {
        if(($key = array_search("Blue", $array)) !== false) 
            unset($array[$key]);

        echo $color . "<br>";

    }

?>

output:

Red
Yellow
Blue
Orange

So as you can see I unset() the array element with the value Blue. But I still have it in my output.

Now my question is: How can I unset the element with the value Blue, so that it directly affects my foreach loop, means I won't see it anymore in the output, since I deleted it before I loop over that specific element.

Expected output would be (Note: Blue is not in the output):

Red
Yellow
Orange

回答1:

You could assign your array by reference to another variable, so that is_ref is 1, means the foreach loop doesn't loop over a copy of your array anymore.

So just put this before your foreach loop:

$arr = &$array;

For more information how foreach actually works see: How does PHP 'foreach' actually work?

Also note, since there are some changes in PHP 7: http://php.net/manual/en/migration70.incompatible.php#migration70.incompatible.foreach this won't work anymore in PHP 7.

If you want to do the same in PHP 7 where the behavior is changed just say that you want to loop through the array by reference, e.g.

foreach($array as &$color)