Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Remove the first and last item of the array

Tags:

arrays

php

Using array_slice is simplest

$newarray = array_slice($array, 1, -1);

If the input array has less than 3 elements in it, the output array will be empty.


To remove the first element, use array_shift, to remove last element, use array_pop:

<?php    
$array = array('10', '20', '30.30', '40', '50');
array_shift($array);
array_pop($array);

array_pop($array); // remove the last element
array_shift($array); // remove the first element

array_slice is going to be the fastest since it's a single function call.

You use it like this: array_slice($input, 1, -1);

Make sure that the array has at least 2 items in it before doing this, though.