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 th开发者_JAVA技巧e 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)
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.
Get the count and subtract 3?
$arr[count($arr)-3]
if (!empty($arr) && count($arr)>1){
//or > 2, -3 for your extra ending
$val = $arr[count($arr)-2];
}
Should help you.
$second_last = count($array) - 3;
$value = $array[$second_last];
$arrayLen=count($arr);
echo $arr[$arrayLen-2];
Yet another alternative:
echo current(array_slice($data, -3, 1));
精彩评论