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

我以为将其设置为null就可以了,但显然它不起作用。


当前回答

unset()数组中的多个碎片元素

虽然这里多次提到unset(),但还需要提到的是,unset(()接受多个变量,从而可以在一次操作中轻松删除数组中的多个非连续元素:

// Delete multiple, noncontiguous elements from an array
$array = [ 'foo', 'bar', 'baz', 'quz' ];
unset( $array[2], $array[3] );
print_r($array);
// Output: [ 'foo', 'bar' ]

动态取消设置()

unset()不接受要删除的键数组,因此下面的代码将失败(但这会使动态使用unset(()稍微容易一些)。

$array = range(0,5);
$remove = [1,2];
$array = unset( $remove ); // FAILS: "unexpected 'unset'"
print_r($array);

相反,unset()可以在foreach循环中动态使用:

$array = range(0,5);
$remove = [1,2];
foreach ($remove as $k=>$v) {
    unset($array[$v]);
}
print_r($array);
// Output: [ 0, 3, 4, 5 ]

通过复制数组来删除数组键

还有一种做法尚待提及。有时,消除某些数组键的最简单方法是将$array1复制到$array2中。

$array1 = range(1,10);
foreach ($array1 as $v) {
    // Remove all even integers from the array
    if( $v % 2 ) {
        $array2[] = $v;
    }
}
print_r($array2);
// Output: [ 1, 3, 5, 7, 9 ];

显然,同样的做法适用于文本字符串:

$array1 = [ 'foo', '_bar', 'baz' ];
foreach ($array1 as $v) {
    // Remove all strings beginning with underscore
    if( strpos($v,'_')===false ) {
        $array2[] = $v;
    }
}
print_r($array2);
// Output: [ 'foo', 'baz' ]

其他回答

遵循默认功能:

PHP:未设置

unset()销毁指定的变量。有关更多信息,请参阅PHP unset

$Array = array("test1", "test2", "test3", "test3");

unset($Array[2]);

PHP:array_pop

函数的作用是删除数组的最后一个元素。有关更多信息,请参阅PHP array_pop

$Array = array("test1", "test2", "test3", "test3");

array_pop($Array);

PHP:array_splice

函数的作用是从数组中删除选定的元素,并用新的元素替换它。有关更多信息,请参阅PHP array_spling

$Array = array("test1", "test2", "test3", "test3");

array_splice($Array,1,2);

PHP:array_shift

函数的作用是从数组中删除第一个元素。有关更多信息,请参阅PHP array_shift

$Array = array("test1", "test2", "test3", "test3");

array_shift($Array);

删除数组元素有不同的方法,其中一些方法对于某些特定任务比其他方法更有用。

删除单个数组元素

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

如果您知道值,但不知道要删除元素的键,可以使用\array_search()获取键。这只在元素不出现多次时有效,因为\array_search只返回第一次命中。

取消设置()

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

代码:

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

输出:

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

\array_splice()方法

如果使用\array_splice(),键将自动重新索引,但关联键不会更改,而不是\array_values(),后者将所有键转换为数字键。

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

代码:

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

输出:

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

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

删除多个数组元素

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

\array_diff()方法

如果您知道要删除的数组元素的值,那么可以使用\array_diff()。与之前使用unset()一样,它不会更改数组的键。

代码:

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

输出:

[
    [1] => b
]

\array_diff_key()方法

如果您知道要删除的元素的键,则需要使用\array_diff_key()。必须确保将关键帧作为第二个参数中的关键帧传递,而不是作为值传递。密钥无法重新索引。

代码:

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

输出:

[
    [1] => b
]

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

\array_filter()方法

如果要删除数组中具有特定值的所有元素,可以使用\array_filter()。

代码:

$array = [0 => "a", 1 => "b", 2 => "c"];
$array = \array_filter($array, static function ($element) {
    return $element !== "b";
    //                   ↑
    // Array value which you want to delete
});

输出:

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

如果指定了索引:

$arr = ['a', 'b', 'c'];
$index = 0;    
unset($arr[$index]);  // $arr = ['b', 'c']

如果我们有值而不是索引:

$arr = ['a', 'b', 'c'];

// search the value to find index
// Notice! this will only find the first occurrence of value
$index = array_search('a', $arr);

if($index !== false){
   unset($arr[$index]);  // $arr = ['b', 'c']
}

if条件是必要的因为如果找不到索引,unset()将自动删除数组的第一个元素,这不是我们想要的。

有两种方法可以删除数组的第一项,同时保持索引的顺序,如果您不知道第一项的键名。

解决方案#1

// 1 is the index of the first object to get
// NULL to get everything until the end
// true to preserve keys
$array = array_slice($array, 1, null, true);

解决方案#2

// Rewinds the array's internal pointer to the first element
// and returns the value of the first array element.
$value = reset($array);
// Returns the index element of the current array position
$key = key($array);
unset($array[$key]);

对于此示例数据:

$array = array(10 => "a", 20 => "b", 30 => "c");

您必须获得以下结果:

array(2) {
  [20]=>
  string(1) "b"
  [30]=>
  string(1) "c"
}

关联阵列

对于关联阵列,请使用unset:

$arr = array('a' => 1, 'b' => 2, 'c' => 3);
unset($arr['b']);

// RESULT: array('a' => 1, 'c' => 3)

数值数组

对于数值数组,请使用array_spling:

$arr = array(1, 2, 3);
array_splice($arr, 1, 1);

// RESULT: array(0 => 1, 1 => 3)

Note

对数值数组使用unset不会产生错误,但会打乱索引:

$arr = array(1, 2, 3);
unset($arr[1]);

// RESULT: array(0 => 1, 2 => 3)