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

I know you can use the "array_pop" to remove the last element in the array. But if I wanted to remove the last 2 or 3 what would I do?

So how would I remove the last 2 elements in this array?

<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_pop($stack);
print_r($stack);
?>

Use array_splice and specify the number of elements which you want to remove.

$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_splice($stack, -2);
print_r($stack);

Output

Array

(
    [0] => orange
    [1] => banana
)

as the rhyme goes: pop twice, or array_slice!

In other words: http://php.net/array_slice

You can use array_slice() with a negative length:

function array_remove($array, $n) {
    return array_slice($array, 0, -$n);
}

Test:

print_r( array_remove($stack, 2) );

Output:

Array
(
    [0] => orange
    [1] => banana
)

In order to remove the last 2 elements of that array, you should use array_slice in this way:

$fruits = array_slice($stack, 0, -2);