Get the First and Last Element in a PHP Array

Get First Element

$first = current(reset($ARRAY));

example

$fruits = array('apple', 'banana', 'cranberry');
$first = current(reset($fruits)); // apple

Remove The First Element

$result = array_shift($ARRAY)

Get Last Element

$last = end($ARRAY); // cranberry

example

$fruits = array('apple', 'banana', 'cranberry');
$last = end($fruits); // cranberry

Remove The Last Element

$result = array_pop($ARRAY)

Remove First and Last Elements

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

example

$fruits = array('apple', 'banana', 'cranberry');
$removed = array_slice($fruits, 1, -1); // banana

Leave a comment

Your email address will not be published. Required fields are marked *