How can I get the element before the last element from an array in PHP5 ?
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.
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.
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.
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.
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.
$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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With