简体   繁体   中英

How to remove the nth element from the end of an array

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
)

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

as the rhyme goes: pop twice, or array_slice!

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

You can just use array_pop() twice. Run it like this:

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

Output:

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

The return value of array_pop() is the element you just removed, not the array . So if you don't need that element anymore, simply call the function as many times as you need and move on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM