开发者

Get second to last value in array

开发者 https://www.devze.com 2022-12-31 02:49 出处:网络
I\'m frequently using the following to get the second to last value in an array: $z=array_pop(array_slice($array,-2,1));

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 ph开发者_如何转开发p function to do that in one go or is that the best I have?


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.


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

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


Or here, should work.

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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消