Reputation: 23244
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?
Upvotes: 21
Views: 28202
Reputation: 22941
Though this is a very old question, I'll add a couple more solutions:
The OP's method is actually fine but the use of array_pop()
is both unneeded and also throws the notice "Only variables should be passed by reference." With that in mind, it's perfectly fine to just do:
$z = array_slice($array, -2, 1);
While the other two methods require the array to be numerically indexed, they still work with the addition of array_values()
which uses very little overhead. I benchmarked these and found not much difference at all with this method:
// index method
$z = array_values($array)[count($array) - 2];
// reverse method
$reverse = array_reverse($array);
$z = array_values($reverse)[1];
Finally, I ran some benchmarks using all the above answers and from my tests, the answer by @Artefacto using end()
and prev()
was *by far the fastest - coming in roughly 2x to 3x faster than all the others.
Upvotes: 1
Reputation: 5007
Or here, should work.
$reverse = array_reverse( $array );
$z = $reverse[1];
I'm using this, if i need it :)
Upvotes: 7
Reputation: 97835
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.
Upvotes: 57
Reputation: 14336
For numerically indexed, consecutive arrays, try $z = $array[count($array)-2];
Edit: For a more generic option, look at Artefecto's answer.
Upvotes: 17