PHP - How to get the element before the last element from an array?

Manny Calavera picture Manny Calavera · Feb 3, 2010 · Viewed 58.9k times · Source

How can I get the element before the last element from an array in PHP5 ?

Answer

Erik picture Erik · Feb 3, 2010

This will work even on this array:

$array[0] = "hello";
$array[5] = "how";
$array[9] = "are";

end($array);
echo prev($array); // will print "how"

The other solutions using count() are assuming that the indexes of your array go in order; by using end and prev to move the array pointer, you get the actual values. Try using the count() method on the array above and it will fail.