18

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,320
  • 11
  • 63
  • 95

3 Answers3

51
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
  • 93,596
  • 16
  • 191
  • 218
  • 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
15

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

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

Philippe Signoret
  • 12,178
  • 1
  • 37
  • 55
6

Or here, should work.

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

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

Xaerxess
  • 26,590
  • 9
  • 85
  • 109
ahmet2106
  • 4,817
  • 4
  • 26
  • 36