【发布时间】:2020-10-01 09:09:48
【问题描述】:
我知道您可以使用“array_pop”来删除数组中的最后一个元素。但如果我想删除最后 2 或 3 个,我会怎么做?
那么我将如何删除该数组中的最后 2 个元素?
<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_pop($stack);
print_r($stack);
?>
【问题讨论】:
我知道您可以使用“array_pop”来删除数组中的最后一个元素。但如果我想删除最后 2 或 3 个,我会怎么做?
那么我将如何删除该数组中的最后 2 个元素?
<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_pop($stack);
print_r($stack);
?>
【问题讨论】:
使用array_splice 并指定要删除的元素数量。
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_splice($stack, -2);
print_r($stack);
输出
数组
(
[0] => orange
[1] => banana
)
【讨论】:
您可以将array_slice() 与否定的length 一起使用:
function array_remove($array, $n) {
return array_slice($array, 0, -$n);
}
测试:
print_r( array_remove($stack, 2) );
输出:
Array
(
[0] => orange
[1] => banana
)
【讨论】:
为了删除该数组的最后 2 个元素,您应该以这种方式使用 array_slice:
$fruits = array_slice($stack, 0, -2);
【讨论】:
正如韵律所说:pop 两次,或者 array_slice!
【讨论】:
您可以只使用 array_pop() 两次。像这样运行它:
<?php
$stack = array("orange", "banana", "apple", "raspberry");
array_pop($stack);
array_pop($stack);
print_r($stack);
?>
输出:
(
[0] => orange
[1] => banana
)
array_pop() 的返回值是你刚刚删除的元素,不是数组。因此,如果您不再需要该元素,只需根据需要多次调用该函数并继续。
【讨论】: