1

I have an array $arr that when I var_dump looks like this. What's the easiest way to get the 2nd last item ('simple' in this case). I can't do $arr[4] because the number of items may vary per url, and I always want just the 2nd last. (note that there's an extra empty string at the end, which will always be there.)

array
  0 => string 'http:' (length=5)
  1 => string '' (length=0)
  2 => string 'site.com'
  3 => string 'group'
  4 => string 'simple'
  5 => string 'some-test-url'
  6 => string '' (length=0)
4
  • 1
    Why not just ask "How do I get the last component of a URL in a string?" instead? Commented Sep 29, 2011 at 21:20
  • Note that second to last and $arr[4] are not the same thing. Unless I'm crazy, I would think that $arr[4] is third to last. Commented Sep 29, 2011 at 21:23
  • @ Ignacio Vazquez-Abrams It's not the last. It's the 2nd last or even the 3rd last if you count the last empty string as an item. Commented Sep 29, 2011 at 21:23
  • As a side note but a very important one: if this is your structure, you should create a Url class for it. I'm sure you have functions that manipulate this array, so they should be methods of your url class. Our coding is often so lax in PHP; as a community we need to get better at using well-proven and structured techniques. Commented Sep 29, 2011 at 21:58

6 Answers 6

3

So long as it is not a keyed or hashed array and it has more than two items...

$arr[count($arr) - 2];

Note: that my interpretation of second to last is second from the end. This may differ from yours. If so, subtract 3.

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

Comments

2

Get the count and subtract 3?

$arr[count($arr)-3]

Comments

2
if (!empty($arr) && count($arr)>1){
  //or > 2, -3 for your extra ending
  $val = $arr[count($arr)-2];
}

Should help you.

Comments

1
$second_last = count($array) - 3;

$value = $array[$second_last];

Comments

1
$arrayLen=count($arr);
echo $arr[$arrayLen-2];

Comments

0

Yet another alternative:

echo current(array_slice($data, -3, 1));

Comments

Your Answer

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.