20

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?

zaf
  • 22,776
  • 12
  • 65
  • 95

4 Answers4

54
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
  • 96,375
  • 17
  • 202
  • 225
  • I like this, better than my answer. :) – Philippe Signoret May 17 '10 at 14:59
  • But for example, if you pass (without ampersand) the array to a function, as your code modifies the internal cursor of the array, it would trigger a copy of the whole array, whereas the "array_slice" method doesn't touch the internal cursor, thus doesn't trigger a copy, and is actually more efficient. Refs [this question](https://stackoverflow.com/questions/2030906/are-arrays-in-php-copied-as-value-or-as-reference-to-new-variables-and-when-pas) for further reading. – Gras Double Jan 03 '22 at 07:18
  • A side effect of using this: it will change to array's internal pointer, if you use the `current()` function afterwards it also give the second last item. – dehart Jan 19 '23 at 10:13
17

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

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

Philippe Signoret
  • 13,299
  • 1
  • 40
  • 58
7

Or here, should work.

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

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

Grzegorz Rożniecki
  • 27,415
  • 11
  • 90
  • 112
ahmet2106
  • 4,957
  • 4
  • 27
  • 38
0

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.