There is an array, the count of the element is unknown,like this:
$arr=['a','m','q','y',....'b','f','n','s'];
How to get the second-to-last element in PHP
?
Eddie
26.8k6 gold badges38 silver badges59 bronze badges
asked May 7, 2018 at 13:46
3 Answers 3
You can use array_slice() like this:
<?php
$arr=['a','m','q','y','b','f','n','s'];
echo array_slice($arr, -2, 1)[0];
Output:
n
Note: this will work regardless of the array type: indexed or associative. So even if the keys are not 0, 1, 2, 3, etc... then this would still work.
answered May 7, 2018 at 13:52
-
1This is the best so far. No need to reinvent stuff if it's the last, second to last or third to last. The code will be the same and just the "-n" is different.Andreas– Andreas2018年05月07日 13:57:16 +00:00Commented May 7, 2018 at 13:57
Since there are no defined keys, it's a little easier:
$second_to_last = $arr[count($arr) - 3];
answered May 7, 2018 at 13:49
-
Hi - it should be "- 2" not "- 3".DRosenfeld– DRosenfeld2022年05月26日 06:59:12 +00:00Commented May 26, 2022 at 6:59
I think this is the answer;
$arr[count($arr)-3]
answered May 7, 2018 at 13:49
lang-php
array_slice
— Extract a slice of the array