简体   繁体   中英

How to get this element from this array

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)

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.

得到计数并减去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];

另一个选择:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM