php 如何在 foreach 循环中删除数组元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1949259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you remove an array element in a foreach loop?
提问by ajsie
I want to loop through an array with foreachto check if a value exists. If the value does exist, I want to delete the element which contains it.
我想遍历一个数组foreach来检查一个值是否存在。如果该值确实存在,我想删除包含它的元素。
I have the following code:
我有以下代码:
foreach($display_related_tags as $tag_name) {
if($tag_name == $found_tag['name']) {
// Delete element
}
}
I don't know how to delete the element once the value is found. How do I delete it?
一旦找到值,我不知道如何删除元素。如何删除它?
I have to use foreachfor this problem. There are probably alternatives to foreach, and you are welcome to share them.
我必须使用foreach这个问题。可能有替代品foreach,欢迎您分享。
回答by Gumbo
If you also get the key, you can delete that item like this:
如果您还获得了密钥,则可以像这样删除该项目:
foreach ($display_related_tags as $key => $tag_name) {
if($tag_name == $found_tag['name']) {
unset($display_related_tags[$key]);
}
}
回答by Neils
A better solution is to use the array_filterfunction:
更好的解决方案是使用该array_filter函数:
$display_related_tags =
array_filter($display_related_tags, function($e) use($found_tag){
return $e != $found_tag['name'];
});
As the php documentationreads:
正如 php文档所写:
As foreach relies on the internal array pointer in PHP 5, changing it within the loop may lead to unexpected behavior.
In PHP 7, foreach does not use the internal array pointer.
由于 foreach 依赖于 PHP 5 中的内部数组指针,因此在循环中更改它可能会导致意外行为。
在 PHP 7 中,foreach 不使用内部数组指针。
回答by Steve H
foreach($display_related_tags as $key => $tag_name)
{
if($tag_name == $found_tag['name'])
unset($display_related_tags[$key];
}
回答by PiotrN
Instead of doing foreach() loop on the array, it would be faster to use array_search() to find the proper key. On small arrays, I would go with foreach for better readibility, but for bigger arrays, or often executed code, this should be a bit more optimal:
不是在数组上执行 foreach() 循环,而是使用 array_search() 来查找正确的键会更快。在小数组上,我会使用 foreach 以获得更好的可读性,但对于更大的数组或经常执行的代码,这应该更优化:
$result=array_search($unwantedValue,$array,true);
if($result !== false) {
unset($array[$result]);
}
The strict comparsion operator !== is needed, because array_search() can return 0 as the index of the $unwantedValue.
需要严格比较运算符 !==,因为 array_search() 可以返回 0 作为 $unwantedValue 的索引。
Also, the above example will remove just the first value $unwantedValue, if the $unwantedValue can occur more then once in the $array, You should use array_keys(), to find all of them:
此外,上面的示例将仅删除第一个值 $unwantedValue,如果 $unwantedValue 可以在 $array 中出现多次,您应该使用 array_keys() 来查找所有这些:
$result=array_keys($array,$unwantedValue,true)
foreach($result as $key) {
unset($array[$key]);
}
Check http://php.net/manual/en/function.array-search.phpfor more information.
回答by Hassan Ali Shahzad
if you have scenario in which you have to remove more then one values from the foreach array in this case you have to pass value by reference in for each: I try to explain this scenario:
如果在这种情况下您必须从 foreach 数组中删除多个值,则必须为每个值通过引用传递值:我尝试解释这种情况:
foreach ($manSkuQty as $man_sku => &$man_qty) {
foreach ($manufacturerSkus as $key1 => $val1) {
// some processing here and unset first loops entries
// here dont include again for next iterations
if(some condition)
unset($manSkuQty[$key1]);
}
}
}
in second loop you want to unset first loops entries dont come again in the iteration for performance purpose or else then unset from memory as well because in memory they present and will come in iterations.
在第二个循环中,您想取消设置第一个循环条目不会在迭代中再次出现以提高性能,否则也会从内存中取消设置,因为在内存中它们存在并且将在迭代中出现。
回答by Somnath Muluk
There are already answers which are giving light on how to unset. Rather than repeating code in all your classes make function like below and use it in code whenever required. In business logic, sometimes you don't want to expose some properties. Please see below one liner call to remove
已经有一些答案可以说明如何取消设置。而不是在您的所有类中重复代码 make 功能如下所示,并在需要时在代码中使用它。在业务逻辑中,有时您不想公开某些属性。请参阅下面的一个班轮电话删除
public static function removeKeysFromAssociativeArray($associativeArray, $keysToUnset)
{
if (empty($associativeArray) || empty($keysToUnset))
return array();
foreach ($associativeArray as $key => $arr) {
if (!is_array($arr)) {
continue;
}
foreach ($keysToUnset as $keyToUnset) {
if (array_key_exists($keyToUnset, $arr)) {
unset($arr[$keyToUnset]);
}
}
$associativeArray[$key] = $arr;
}
return $associativeArray;
}
Call like:
像这样调用:
removeKeysFromAssociativeArray($arrValues, $keysToRemove);
回答by Ciarán Walsh
As has already been mentioned, you'd want to do a foreach with the key, and unset using the key – but note that mutating an array during iteration is in general a bad idea, though I'm not sure on PHP's rules on this offhand.
正如已经提到的,您想使用键执行 foreach,并使用键取消设置 - 但请注意,在迭代期间改变数组通常是一个坏主意,尽管我不确定 PHP 对此的规则随手。

