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

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


当前回答

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

    echo $fruit;
?>

输出:

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

fruit1

其他回答

Edit

如果无法将其视为对象位于该数组中,则需要添加检查:

if(in_array($object,$array)) unset($array[array_search($object,$array)]);

原始答案

如果要通过引用数组中的特定对象来删除该对象,可以执行以下操作:

unset($array[array_search($object,$array)]);

例子:

<?php
class Foo
{
    public $id;
    public $name;
}

$foo1 = new Foo();
$foo1->id = 1;
$foo1->name = 'Name1';

$foo2 = new Foo();
$foo2->id = 2;
$foo2->name = 'Name2';

$foo3 = new Foo();
$foo3->id = 3;
$foo3->name = 'Name3';


$array = array($foo1,$foo2,$foo3);
unset($array[array_search($foo2,$array)]);

echo '<pre>';
var_dump($array);
echo '</pre>';
?>

结果:

array(2) {
[0]=>
    object(Foo)#1 (2) {
        ["id"]=>
        int(1)
        ["name"]=>
        string(5) "Name1"
    }
[2]=>
    object(Foo)#3 (2) {
        ["id"]=>
        int(3)
        ["name"]=>
        string(5) "Name3"
    }
}

请注意,如果对象多次出现,则只会在第一次出现时删除它!

此外,对于命名元素:

unset($array["elementName"]);

解决:

要删除一个元素,请使用unset():

未设置($array[3]);unset($array['fo']);

要删除多个不连续的元素,还可以使用unset():

未设置($array[3],$array[5]);取消设置($array['fo'],$array['bar']);

要删除多个连续元素,请使用array_splice():

array_拼接($array,$offset,$length);

进一步解释:

使用这些函数可以从PHP中删除对这些元素的所有引用。如果要在数组中保留一个键,但该键的值为空,请将空字符串分配给元素:

$array[3] = $array['foo'] = '';

除了语法之外,使用unset()和将“”赋值给元素之间还有逻辑上的区别。第一个表示This已不存在,而第二个表示This仍然存在,但其值为空字符串。

如果你在处理数字,分配0可能是更好的选择。因此,如果一家公司停止生产XL1000型链轮,它将更新库存:

unset($products['XL1000']);

然而,如果XL1000链轮暂时用完,但计划在本周晚些时候从工厂接收新的发货,则情况会更好:

$products['XL1000'] = 0;

如果取消设置()元素,PHP将调整数组,以便循环仍然正常工作。它不会压缩阵列以填充缺失的孔。这就是我们所说的所有数组都是关联的,即使它们看起来是数字。下面是一个示例:

// Create a "numeric" array
$animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');
print $animals[1];  // Prints 'bee'
print $animals[2];  // Prints 'cat'
count($animals);    // Returns 6

// unset()
unset($animals[1]); // Removes element $animals[1] = 'bee'
print $animals[1];  // Prints '' and throws an E_NOTICE error
print $animals[2];  // Still prints 'cat'
count($animals);    // Returns 5, even though $array[5] is 'fox'

// Add a new element
$animals[ ] = 'gnu'; // Add a new element (not Unix)
print $animals[1];  // Prints '', still empty
print $animals[6];  // Prints 'gnu', this is where 'gnu' ended up
count($animals);    // Returns 6

// Assign ''
$animals[2] = '';   // Zero out value
print $animals[2];  // Prints ''
count($animals);    // Returns 6, count does not decrease

要将数组压缩为填充密集的数字数组,请使用array_values():

$animals = array_values($animals);

或者,array_splice()会自动重新索引数组以避免留下洞:

// Create a "numeric" array
$animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');
array_splice($animals, 2, 2);
print_r($animals);
Array
(
    [0] => ant
    [1] => bee
    [2] => elk
    [3] => fox
)

如果您将数组用作队列,并希望从队列中删除项目,同时仍允许随机访问,则这非常有用。要安全地从数组中删除第一个或最后一个元素,请分别使用array_shift()和array_pop()。

销毁阵列的单个元素

取消设置()

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

输出将为:

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

如果需要重新索引阵列:

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

那么输出将是:

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

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

混合数组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

输出将为

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

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

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

输出将为:

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

遵循默认功能:

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