Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - How to get the element before the last element from an array?

How can I get the element before the last element from an array in PHP5 ?

like image 961
Manny Calavera Avatar asked Feb 03 '10 18:02

Manny Calavera


People also ask

How can get first and last value in array in PHP?

You can use the end() function in PHP to get the last element of any PHP array. It will set the internal pointer to the last element of the array and return its value.

How do I find the second last element in an array?

To get the second to last element in an array, call the at() method on the array, passing it -2 as a parameter, e.g. arr.at(-2) . The at method returns the array element at the specified index. When passed a negative index, the at() method counts back from the last item in the array.

How do you check if the element is last element in an array in PHP?

The end() function is an inbuilt function in PHP and is used to find the last element of the given array. The end() function changes the internal pointer of an array to point to the last element and returns the value of the last element.

How do I find the first and last elements of 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.


2 Answers

This will work even on this array:

$array[0] = "hello"; $array[5] = "how"; $array[9] = "are";  end($array); echo prev($array); // will print "how" 

The other solutions using count() are assuming that the indexes of your array go in order; by using end and prev to move the array pointer, you get the actual values. Try using the count() method on the array above and it will fail.

like image 141
Erik Avatar answered Sep 28 '22 00:09

Erik


$array[count($array)-2] 

It should be a numerically indexed array (from zero). You should have at least 2 elements for this to work. (obviously)

like image 30
Notinlist Avatar answered Sep 28 '22 01:09

Notinlist