zaf
zaf

Reputation: 23244

Get second to last value in array

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

Answers (4)

You Old Fool
You Old Fool

Reputation: 22941

Though this is a very old question, I'll add a couple more solutions:

OP's method:

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);

Methods that require numerically indexed array:

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

ahmet2106
ahmet2106

Reputation: 5007

Or here, should work.

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

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

Upvotes: 7

Artefacto
Artefacto

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

Philippe Signoret
Philippe Signoret

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

Related Questions