如何从数组中删除特定值的多个实例

时间:2018-08-16 15:54:09

标签: php

我试图从数组中取消设置特定值的每个实例,但是我只能取消设置该值的第一个实例。如何删除所有值等于我要搜索的内容?

$toRemove = array("red","blue");
$myArray = array("red", "green", "blue", "blue", "blue", "purple", "yellow");

foreach ($toRemove as $remove)
{
    if (($key = array_search($remove, $myArray)) !== false)
    {
        unset($myArray[$key];
    }
}
print_r($myArray);

上面只是将其作为我的数组值返回:

array("green", "blue", "blue", "purple", "yellow");

1 个答案:

答案 0 :(得分:1)

只需计算差异:

$myArray = array_diff($myArray, $toRemove);

但是,您当前的代码仅返回一个键,因此您需要搜索更多键。您可以使用while

foreach ($toRemove as $remove)
{
    while (($key = array_search($remove, $myArray)) !== false)
    {
        unset($myArray[$key]);
    }
}

或者获取所有密钥并循环它们:

foreach ($toRemove as $remove)
{
    foreach (array_keys($myArray, $remove) as $key)
    {
        unset($myArray[$key]);
    }
}