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

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


当前回答

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

解决方案#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()数组中的多个碎片元素

虽然这里多次提到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' ]

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

解决方案#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"
}

使用以下代码:

$arr = array('orange', 'banana', 'apple', 'raspberry');
$result = array_pop($arr);
print_r($result);

我来这里是因为我想看看是否有比使用unset($arr[$I])更优雅的解决方案来解决这个问题。令我失望的是,这些答案要么是错误的,要么没有涵盖所有边缘情况。

这就是array_diff()不起作用的原因。键在数组中是唯一的,而元素并不总是唯一的。

$arr = [1,2,2,3];

foreach($arr as $i => $n){
    $b = array_diff($arr,[$n]);
    echo "\n".json_encode($b);
}

后果

[2,2,3]
[1,3]
[1,2,2] 

如果两个元素相同,则将删除它们。这也适用于array_search()和array_flip()。

我看到了很多关于array_slice()和array_splice()的答案,但这些函数只适用于数值数组。如果这里没有回答这个问题,我知道所有的答案,所以这里有一个可行的解决方案。

$arr = [1,2,3];

foreach($arr as $i => $n){
    $b = array_merge(array_slice($arr,0,$i),array_slice($arr,$i+1));
    echo "\n".json_encode($b);
}

Results...

[2,3];
[1,3];
[1,2];

由于unset($arr[$i])将同时适用于关联数组和数值数组,所以这仍然不能回答这个问题。

这个解决方案是比较键和,使用一个同时处理数字和关联数组的工具。为此,我使用了array_diff_uassoc()。此函数用于比较回调函数中的按键。

$arr = [1,2,2,3];
//$arr = ['a'=>'z','b'=>'y','c'=>'x','d'=>'w'];
foreach($arr as $key => $n){
    $b = array_diff_uassoc($arr, [$key=>$n], function($a,$b) {
        if($a != $b){
            return 1;
        }
    });
    echo "\n".json_encode($b);
}    

后果

[2,2,3];
[1,2,3];
[1,2,2];

['b'=>'y','c'=>'x','d'=>'w'];
['a'=>'z','c'=>'x','d'=>'w'];
['a'=>'z','b'=>'y','d'=>'w'];
['a'=>'z','b'=>'y','c'=>'x'];

遵循默认功能:

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);