Theodore R. Smith Theodore R. Smith - 5 months ago 8
PHP Question

What's the best way to get the last element of an array without deleting it?

Ok,

I know all about

, but that deletes the last element. What's the best way to get the last element of an array without deleting it?

EDIT: Here's a bonus:

$array = array('a' => 'a', 'b' => 'b', 'c' => 'c');


or even

$array = array('a', 'b', 'c', 'd');
unset($array[2]);
echo $array[sizeof($array) - 1]; // Output: PHP Notice: Undefined offset: 2 in - on line 4

Answer

Short and sweet.

$lastEl = array_pop((array_slice($array, -1)));

Note: The extra parentheses are needed to avoid a PHP Strict standards: Only variables should be passed by reference.

Comments