PHP 删除数组中的元素

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

Deleting an element from an array in PHP

phparraysunset

提问by Ben

Is there an easy way to delete an element from an array using PHP, such that foreach ($array)no longer includes that element?

有没有一种简单的方法可以使用 PHP 从数组中删除元素,从而foreach ($array)不再包含该元素?

I thought that setting it to nullwould do it, but apparently it does not work.

我认为将其设置为null可以做到这一点,但显然它不起作用。

回答by Konrad Rudolph

There are different ways to delete an array element, where some are more useful for some specific tasks than others.

有多种方法可以删除数组元素,其中一些方法对某些特定任务比其他方法更有用。

Delete one array element

删除一个数组元素

If you want to delete just one array element you can use unset()or alternatively \array_splice().

如果您只想删除一个数组元素,您可以使用unset()\array_splice()

Also if you have the value and don't know the key to delete the element you can use \array_search()to get the key.

此外,如果您拥有该值但不知道删除元素的键,您可以使用\array_search()该键来获取该键。

unset()

unset()

Note that when you use unset()the array keys won't change/reindex. If you want to reindex the keys you can use \array_values()after unset()which will convert all keys to numerical enumerated keys starting from 0.

请注意,当您使用unset()数组键时,不会更改/重新索引。如果您想重新索引您可以使用的键,\array_values()之后unset()会将所有键转换为从 0 开始的数字枚举键。

Code

代码

<?php

    $array = [0 => "a", 1 => "b", 2 => "c"];
    unset($array[1]);
                //↑ Key which you want to delete

?>

Output

输出

[
    [0] => a
    [2] => c
]

\array_splice()method

\array_splice()方法

If you use \array_splice()the keys will be automatically reindexed, but the associative keys won't change as opposed to \array_values()which will convert all keys to numerical keys.

如果您使用\array_splice()这些键将自动重新索引,但关联键不会改变,相反\array_values()会将所有键转换为数字键。

Also \array_splice()needs the offset, not the key! as the second parameter.

\array_splice()需要偏移量,而不是关键!作为第二个参数。

Code

代码

<?php

    $array = [0 => "a", 1 => "b", 2 => "c"];
    \array_splice($array, 1, 1);
                        //↑ Offset which you want to delete

?>

Output

输出

[
    [0] => a
    [1] => c
]

array_splice()same as unset()take the array by reference, and this means you don't want to assign the return values of those functions back to the array.

array_splice()unset()通过引用获取数组相同,这意味着您不想将这些函数的返回值分配回数组。

Delete multiple array elements

删除多个数组元素

If you want to delete multiple array elements and don't want to call unset()or \array_splice()multiple times you can use the functions \array_diff()or \array_diff_key()depending on if you know the values or the keys of the elements which you want to delete.

如果您想删除多个数组元素并且不想调用unset()\array_splice()多次调用,您可以使用这些函数,\array_diff()或者\array_diff_key()取决于您是否知道要删除的元素的值或键。

\array_diff()method

\array_diff()方法

If you know the values of the array elements which you want to delete, then you can use \array_diff(). As before with unset()it won't change/reindex the keys of the array.

如果您知道要删除的数组元素的值,则可以使用\array_diff(). 和以前一样,unset()它不会更改/重新索引数组的键。

Code

代码

<?php

    $array = [0 => "a", 1 => "b", 2 => "c"];
    $array = \array_diff($array, ["a", "c"]);
                               //└────────┘→ Array values which you want to delete

?>

Output

输出

[
    [1] => b
]

\array_diff_key()method

\array_diff_key()方法

If you know the keys of the elements which you want to delete, then you want to use \array_diff_key(). Here you have to make sure you pass the keys as keys in the second parameter and not as values. Otherwise, you have to flip the array with \array_flip(). And also here the keys won't change/reindex.

如果您知道要删除的元素的键,那么您想使用\array_diff_key(). 在这里,您必须确保将键作为第二个参数中的键而不是作为值传递。否则,您必须使用\array_flip(). 而且这里的键不会改变/重新索引。

Code

代码

<?php

    $array = [0 => "a", 1 => "b", 2 => "c"];
    $array = \array_diff_key($array, [0 => "xy", "2" => "xy"]);
                                    //↑           ↑ Array keys which you want to delete
?>

Output

输出

[
    [1] => b
]

Also if you want to use unset()or \array_splice()to delete multiple elements with the same value you can use \array_keys()to get all the keys for a specific value and then delete all elements.

此外,如果您想使用unset()\array_splice()删除具有相同值的多个元素,您可以使用\array_keys()获取特定值的所有键,然后删除所有元素。

回答by Stefan Gehrig

It should be noted that unset()will keep indexes untouched, which is what you'd expect when using string indexes (array as hashtable), but can be quite surprising when dealing with integer indexed arrays:

应该注意的是,unset()将保持索引不变,这是您在使用字符串索引(数组作为哈希表)时所期望的,但在处理整数索引数组时可能会非常令人惊讶:

$array = array(0, 1, 2, 3);
unset($array[2]);
var_dump($array);
/* array(3) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [3]=>
  int(3)
} */

$array = array(0, 1, 2, 3);
array_splice($array, 2, 1);
var_dump($array);
/* array(3) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(3)
} */

So array_splice()can be used if you'd like to normalize your integer keys. Another option is using array_values()after unset():

所以array_splice()如果你想规范化你的整数键,可以使用它。另一种选择是使用array_values()after unset()

$array = array(0, 1, 2, 3);

unset($array[2]);
$array = array_values($array);
var_dump($array);
/* array(3) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(3)
} */

回答by Marcel Cozma

  // Our initial array
  $arr = array("blue", "green", "red", "yellow", "green", "orange", "yellow", "indigo", "red");
  print_r($arr);

  // Remove the elements who's values are yellow or red
  $arr = array_diff($arr, array("yellow", "red"));
  print_r($arr);

This is the output from the code above:

这是上面代码的输出:

Array
(
    [0] => blue
    [1] => green
    [2] => red
    [3] => yellow
    [4] => green
    [5] => orange
    [6] => yellow
    [7] => indigo
    [8] => red
)

Array
(
    [0] => blue
    [1] => green
    [4] => green
    [5] => orange
    [7] => indigo
)

Now, array_values() will reindex a numerical array nicely, but it will remove all key strings from the array and replace them with numbers. If you need to preserve the key names (strings), or reindex the array if all keys are numerical, use array_merge():

现在,array_values() 将很好地重新索引一个数字数组,但它会从数组中删除所有关键字符串并用数字替换它们。如果您需要保留键名(字符串),或者在所有键都是数字的情况下重新索引数组,请使用 array_merge():

$arr = array_merge(array_diff($arr, array("yellow", "red")));
print_r($arr);

Outputs

输出

Array
(
    [0] => blue
    [1] => green
    [2] => green
    [3] => orange
    [4] => indigo
)

回答by liamvictor

$key = array_search($needle, $array);
if ($key !== false) {
    unset($array[$key]);
}

回答by Eran Galperin

unset($array[$index]);

回答by Robin Nixon

If you have a numerically indexed array where all values are unique (or they are non-unique but you wish to remove all instances of a particular value), you can simply use array_diff() to remove a matching element, like this:

如果您有一个数字索引数组,其中所有值都是唯一的(或者它们不唯一但您希望删除特定值的所有实例),您可以简单地使用 array_diff() 删除匹配元素,如下所示:

$my_array = array_diff($my_array, array('Value_to_remove'));

For example:

例如:

$my_array = array('Andy', 'Bertha', 'Charles', 'Diana');
echo sizeof($my_array) . "\n";
$my_array = array_diff($my_array, array('Charles'));
echo sizeof($my_array);

This displays the following:

这将显示以下内容:

4
3

In this example, the element with the value 'Charles' is removed as can be verified by the sizeof() calls that report a size of 4 for the initial array, and 3 after the removal.

在此示例中,删除了值为 'Charles' 的元素,这可以通过 sizeof() 调用进行验证,该调用报告初始数组的大小为 4,删除后为 3。

回答by DefenestrationDay

Also, for a named element:

此外,对于命名元素:

unset($array["elementName"]);

回答by Saurabh Chandra Patel

<?php
    $stack = ["fruit1", "fruit2", "fruit3", "fruit4"];
    $fruit = array_shift($stack);
    print_r($stack);

    echo $fruit;
?>

Output:

输出:

[
    [0] => fruit2
    [1] => fruit3
    [2] => fruit4
]

fruit1

回答by KTAnj

Destroy a single element of an array

销毁数组的单个元素

unset()

unset()

$array1 = array('A', 'B', 'C', 'D', 'E');
unset($array1[2]); // Delete known index(2) value from array
var_dump($array1);

The output will be:

输出将是:

array(4) {
  [0]=>
  string(1) "A"
  [1]=>
  string(1) "B"
  [3]=>
  string(1) "D"
  [4]=>
  string(1) "E"
}

If you need to re index the array:

如果您需要重新索引数组:

$array1 = array_values($array1);
var_dump($array1);

Then the output will be:

然后输出将是:

array(4) {
  [0]=>
  string(1) "A"
  [1]=>
  string(1) "B"
  [2]=>
  string(1) "D"
  [3]=>
  string(1) "E"
}

Pop the element off the end of array- return the value of the removed element

从数组末尾弹出元素- 返回删除元素的值

mixed array_pop(array &$array)

mixed array_pop(array &$array)

$stack = array("orange", "banana", "apple", "raspberry");
$last_fruit = array_pop($stack);
print_r($stack);
print_r('Last Fruit:'.$last_fruit); // Last element of the array

The output will be

输出将是

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
)
Last Fruit: raspberry

Remove the first element (red) from an array, - return the value of the removed element

从数组中移除第一个元素(红色), - 返回移除元素的值

mixed array_shift ( array &$array )

mixed array_shift ( array &$array )

$color = array("a" => "red", "b" => "green" , "c" => "blue");
$first_color = array_shift($color);
print_r ($color);
print_r ('First Color: '.$first_color);

The output will be:

输出将是:

Array
(
    [b] => green
    [c] => blue
)
First Color: red

回答by Mugoma J. Okomba

To avoid doing a search one can play around with array_diff:

为了避免进行搜索,可以玩弄array_diff

$array = array(3, 9, 11, 20);
$array = array_diff($array, array(11) ); // removes 11

In this case one doesn't have to search/use the key.

在这种情况下,不必搜索/使用密钥。