我怎样才能改变我的数组,直接影响我的foreach循环? [英] How can I change my array, which directly affects my foreach loop?
问题描述
pre $
<?php
$ array = [Red,Yellow,Blue,Orange ];
$ b foreach($ array as $ color){
if(($ key = array_search(Blue,$ array))!== false)
unset($ array [$键]);
echo $ color。 <峰; br> 中;
}
?>
输出:
红色
黄色
蓝色
橙色
所以你可以看到我 unset()
值为 Blue
的数组元素。但我仍然在我的输出中。
现在我的问题是:如何取消设置值 预期的输出是(注意:蓝色不在输出中): 您可以通过引用另一个变量来分配数组,这样 所以,只要把它放在你的foreach循环之前就可以了: 有关更多信息,请参阅: PHP的foreach实际上是如何工作的? 另外请注意,因为有一些PHP 7中的更改: http://php.net/manual /en/migration70.incompatible.php#migration70.incompatible.foreach 这将不再适用于PHP 7。 如果你想要做同样的事情在PHP 7中的行为改变只是说,你要通过引用循环访问数组,例如 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: output: So as you can see I Now my question is: How can I unset the element with the value Expected output would be (Note: Blue is not in the output):
You could assign your array by reference to another variable, so that So just put this before your foreach loop: 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循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!蓝色$ c $因为它直接直接影响我的foreach循环,意味着我不会在输出中看到它,因为我在之前删除了我遍历该特定元素。
Red
Yellow
Orange
is_ref
是1,意味着foreach循环不会遍历数组副本。
$ arr =& $ array;
foreach($ array as& $ color)
<?php
$array = ["Red", "Yellow", "Blue", "Orange"];
foreach($array as $color) {
if(($key = array_search("Blue", $array)) !== false)
unset($array[$key]);
echo $color . "<br>";
}
?>
Red
Yellow
Blue
Orange
unset()
the array element with the value Blue
. But I still have it in my output.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.Red
Yellow
Orange
is_ref
is 1, means the foreach loop doesn't loop over a copy of your array anymore. $arr = &$array;
foreach($array as &$color)