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

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


当前回答

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

其他回答

unset()销毁指定的变量。

函数内部unset()的行为可能会因试图销毁的变量类型而异。

如果函数内部的全局变量未设置(),则只销毁局部变量。调用环境中的变量将保持与调用unset()之前相同的值。

<?php
    function destroy_foo()
    {
        global $foo;
        unset($foo);
    }

    $foo = 'bar';
    destroy_foo();
    echo $foo;
?>

以上代码的答案将为bar。

要取消设置()函数内部的全局变量,请执行以下操作:

<?php
    function foo()
    {
        unset($GLOBALS['bar']);
    }

    $bar = "something";
    foo();
?>

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

解决方案#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"
}
$key = array_search($needle, $array);
if ($key !== false) {
    unset($array[$key]);
}

使用以下代码:

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

遵循默认功能:

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