简体   繁体   English

php:如何获取数组的倒数第二个元素?

[英]php: How to get the second-to-last element of an array?

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 ? 如何在PHP获得倒数第二个元素?

You can use array_slice() like this: 您可以像这样使用array_slice()

<?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. 因此,即使键不是0,1,2,3等......那么这仍然有效。

由于没有定义的键,因此更容易:

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

我认为这就是答案;

$arr[count($arr)-3]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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