从 PHP 数组中删除字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4120589/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:02:36  来源:igfitidea点击:

Remove string from PHP array?

phparraysstring

提问by Zac Brown

Is it possible to remove a string (see example below) from a PHP array without knowing the index?

是否可以在不知道索引的情况下从 PHP 数组中删除字符串(参见下面的示例)?

Example:

例子:

array = array("string1", "string2", "string3", "string4", "string5");

I need to remove string3.

我需要删除string3。

回答by GWW

$index = array_search('string3',$array);
if($index !== FALSE){
    unset($array[$index]);
}

if you think your value will be in there more than once try using array_keyswith a search value to get all of the indexes. You'll probably want to make sure

如果您认为您的值会出现不止一次,请尝试使用带有搜索值的array_keys来获取所有索引。你可能想确保

EDIT:

编辑:

Note, that indexes remain unchanged when using unset. If this is an issue, there is a nice answer herethat shows how to do this using array_splice.

请注意,使用unset. 如果这是一个问题,有一个很好的答案在这里展示了如何使用做到这一点array_splice

回答by ABorty

You can do this.

你可以这样做。

$arr = array("string1", "string2", "string3", "string4", "string5");
$new_arr=array();
foreach($arr as $value)
{
    if($value=="string3")
    {
        continue;
    }
    else
    {
        $new_arr[]=$value;
    }     
}
print_r($new_arr); 

回答by Dustin Poissant

Use a combination of array_searchand array_splice.

使用的组合array_searcharray_splice

function array_remove(&$array, $item){
  $index = array_search($item, $array);
  if($index === false)
    return false;
  array_splice($array, $index, 1);
  return true;
}

回答by Mikael Gr?n

This is probably not the fastest method, but it's a short and neat one line of code:

这可能不是最快的方法,但它是一行简短而整洁的代码:

$array = array_diff($array, array("string3"))

or if you're using PHP >5.4.0 or higher:

或者如果您使用的是 PHP > 5.4.0 或更高版本:

$array = array_diff($array, ["string3"])

回答by Sheetal Mehra

You can also try like this.

你也可以这样试试。

$array = ["string1", "string2", "string3", "string4", "string5"];
$key = array_search('string3',$array);
unset($array[$key]);

回答by Arantor

It sort of depends how big the array is likely to be, and there's multiple options.

这有点取决于阵列可能有多大,并且有多种选择。

If it's typically quite small, array_diff is likely the fastest consistent solution, as Jorge posted.

如果它通常很小,那么 array_diff 可能是最快的一致解决方案,正如 Jorge 发布的那样。

Another solution for slightly larger sets:

稍微大一点的集合的另一种解决方案:

$data = array_flip($data);
unset($data[$item2remove]);
$data = array_flip($data);

But that's only good if you don't have duplicate items. Depending on your workload it might be advantageous to guarantee uniqueness of items too.

但这只有在您没有重复的项目时才有用。根据您的工作量,保证项目的唯一性也可能是有利的。