Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the most efficient way to array_pop() the last n elements in an array?

What's an efficient way to pop the last n elements in an array?

Here's one:

$arr = range(1,10);
$n = 2;
$popped_array = array();
for ($i=0; $i < $n; $i++) { 
    $popped_array[] = array_pop($arr);
}
print_r($popped_array); // returns array(10,9);

Is there a more efficient way?

like image 817
Ryan Avatar asked Jan 08 '14 15:01

Ryan


People also ask

How do you find the last element of an array?

1) Using the array length property The length property returns the number of elements in an array. Subtracting 1 from the length of an array gives the index of the last element of an array using which the last element can be accessed.

How to remove last element of an array in PHP?

The array_pop() function deletes the last element of an array.

What does pop() do js?

pop() The pop() method removes the last element from an array and returns that element. This method changes the length of the array.

How to use pop in an array?

JavaScript Array pop()The pop() method removes (pops) the last element of an array. The pop() method changes the original array. The pop() method returns the removed element.


2 Answers

Use array_splice():

If you're trying to remove the last n elements, use the following function:

function array_pop_n(array $arr, $n) {
    return array_splice($arr, 0, -$n);
}

Demo


If you want to retrieve only the last n elements, then you can use the following function:

function array_pop_n(array $arr, $n) {
    array_splice($arr,0,-$n);
    return $arr;
}

Demo

like image 106
Amal Murali Avatar answered Oct 19 '22 22:10

Amal Murali


It's important to note, looking at the other answers, that array_slice will leave the original array alone, so it will still contain the elements at the end, and array_splice will mutate the original array, removing the elements at the beginning (though in the example given, the function creates a copy, so the original array still would contain all elements). If you want something that literally mimics array_pop (and you don't require the order to be reversed, as it is in your OP), then do the following.

$arr = range(1, 10);
$n = 2;
$popped_array = array_slice($arr, -$n);
$arr = array_slice($arr, 0, -$n);
print_r($popped_array); // returns array(9,10);
print_r($arr); // returns array(1,2,3,4,5,6,7,8);

If you require $popped_array to be reversed, array_reverse it, or just pop it like your original example, it's efficient enough as is and much more direct.

like image 45
Jason Avatar answered Oct 19 '22 22:10

Jason