3

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
  • 2
    calculate the lenght of the array with count() and then it is trivial Commented May 7, 2018 at 13:48
  • Maybe are you looking for array_splice? Commented May 7, 2018 at 13:49
  • array_slice — Extract a slice of the array Commented May 7, 2018 at 13:49

3 Answers 3

10

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
1
  • 1
    This 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. Commented May 7, 2018 at 13:57
2

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
1
  • Hi - it should be "- 2" not "- 3". Commented May 26, 2022 at 6:59
1

I think this is the answer;

$arr[count($arr)-3]
answered May 7, 2018 at 13:49

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.