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?

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
2

Since there are no defined keys, it's a little easier:

$second_to_last = $arr[count($arr) - 3]; 

1 Comment

Hi - it should be "- 2" not "- 3".
1

I think this is the answer;

$arr[count($arr)-3] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.