php - 如何从数组末尾删除第n个元素

标签 php arrays

我知道您可以使用“array_pop”删除数组中的最后一个元素。但是,如果我想删除最后 2 或 3 个,我该怎么办?

那么我该如何删除这个数组中的最后两个元素呢?

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

关于php - 如何从数组末尾删除第n个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20621345/

相关文章:

php - MySQL Left join 使查询非常慢......我该如何重构?

java - 我如何找到 int 数组中最小值的索引?

c++ - 在 C++ 中,如何从函数返回对象数组?

Java教科书: "the size of an array must be known at compile time"

php - 是否有必要在 PHP 中初始化/声明变量?

php - 从两个 MySQL 表中提取

php - 缓存相关数据的模式

arrays - 将 x 元素移动到数组的末尾

c - C中的数组求和,应该在(???)中插入什么来完成该功能?

php - 将自定义 float 添加到现有的 wordpress 模板而不会损坏