tags:

views:

113

answers:

3

I'm frequently using the following to get the second to last value in an array:

$z=array_pop(array_slice($array,-2,1));

Am I missing a php function to do that in one go or is that the best I have?

+9  A: 

For numerically indexed, consecutive arrays, try $z = $array[count($array)-2];

Edit: For a more generic option, look at Artefecto's answer.

Philippe Signoret
You beat me to it! =)
pr1001
I just got lucky... :)
Philippe Signoret
Only works if the array is indexed numerically, it starts with 0 and there are no gaps.
Artefacto
Good point. I'll edit accordingly.
Philippe Signoret
+10  A: 
end($array);
$z = prev($array);

This is more efficient than your solution because it relies on the array's internal pointer. Your solution does an uncessary copy of the array.

Artefacto
I like this, better than my answer. :)
Philippe Signoret
A: 

Or here, should work.

$reverse = array_reverse( $array ); $z = $reverse[1];

I'm using this, if i need it :)

ahmet2106