Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the last element of an array without changing the array in PHP?

Tags:

arrays

php

array_pop() removes it from the array. end() changes the internal pointer.

Is the only way really some cludge like:

$my_array[array_pop(array_keys($my_array))];

?

like image 811
Joren Avatar asked Sep 20 '11 19:09

Joren


1 Answers

This works:

list($end) = array_slice($array, -1);

array_slice($array, -1) returns an array with just the last element and list() assigns the first element of slice's result to $end.

@Alin Purcaru suggested this one in comments:

$end = current(array_slice($array, -1));

Since PHP 5.4, this works too:

array_slice($array, -1)[0]
like image 142
Arnaud Le Blanc Avatar answered Oct 05 '22 20:10

Arnaud Le Blanc