views:

345

answers:

4

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

+6  A: 
$array[count($array)-2]

It should be a numerically indexed array (from zero). You should have at least 2 elements for this to work. (obviously)

Notinlist
Thank you. And all.
Manny Calavera
Erik's answer is more correct, not only does it account for the case he indicated with non-sequential keys, but will work with associative arrays as well (Arrays with strings as keys)
Wally Lawless
+14  A: 

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.

Erik
+1  A: 

A method that will work for both associative array and numeric array is to use array_pop() to pop the element off the end of array.

$last = array_pop($array);
$second_last = array_pop($array);

// put back the last
array_push($array, $last);
Yada
+1  A: 

array_slice takes a negative offset as the second argument. This will give you a single item array containing the second last item:

$arr = array(1,2,3,4,5,6);
array_slice($arr, -2, 1));

If you just want the single value on it's own you have several options. If you don't mind using an intermediate variable you can then just get the first value with [0] or call array_pop or array_shift, they both need a variable passed by reference or you'll get warnings in strict mode.

Or you could just use array_sum or array_product, which is a bit hacky but works fine for single item arrays.

James Wheare