Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

php

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);
?>
like image 829
Nic Avatar asked Nov 01 '25 08:11

Nic


2 Answers

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
)
like image 149
Noor Avatar answered Nov 03 '25 00:11

Noor


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
)
like image 27
Amal Murali Avatar answered Nov 02 '25 23:11

Amal Murali