Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get second to last value in array

Tags:

arrays

php

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?

like image 933
zaf Avatar asked May 17 '10 14:05

zaf


People also ask

What is the index value of the second element in an array?

Referring to array elements You can refer to the first element of the array as myArray[0] , the second element of the array as myArray[1] , etc… The index of the elements begins with zero. Note: You can also use property accessors to access other properties of the array, like with an object.

How do I find the first and last value in an array?

To get the first and last elements of an array, access the array at index 0 and the last index. For example, arr[0] returns the first element, whereas arr[arr. length - 1] returns the last element of the array.

How do I find the last value in an array?

1) Using the array length property The length property returns the number of elements in an array. Subtracting 1 from the length of an array gives the index of the last element of an array using which the last element can be accessed.

How do you add elements to the last of an array?

When you want to add an element to the end of your array, use push(). If you need to add an element to the beginning of your array, try unshift(). And you can add arrays together using concat().


3 Answers

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.

like image 172
Artefacto Avatar answered Oct 22 '22 10:10

Artefacto


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

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

like image 24
Philippe Signoret Avatar answered Oct 22 '22 10:10

Philippe Signoret


Or here, should work.

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

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

like image 6
ahmet2106 Avatar answered Oct 22 '22 08:10

ahmet2106