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