php - 获取 PHP 数组中的最后一个数字索引

标签 php arrays

我有一个 PHP 数组,它包含不同数量的元素和不同类型的关联,如下所示:

$example =
Array
(
    [0] => 12345
    [1] => 100
    [2] => Some String

    ...

    [17] => 2
    [18] => 0
    [type] => Some String
    [inst] => Array
        (
            [0] => Some String
        )
    [method] => Some String

)

$other = 
Array
(
    [0] => 45678
    [1] => 250
    [2] => Some String

    ...

    [8] => 7
    [9] => -2
    [inst] => Array
        (
            [0] => Some String
            [1] => Some String
        )

)

我想要做的是获取这些数组中的最后一个数字索引以及之前的一些数字索引。例如,在第一个示例中,我想获取 $example[18],在第二个示例中,我想返回 $other[9]

在命名关联发挥作用之前,我使用的是 count($array)-1

最佳答案

使用 max array_keys

echo max(array_keys($array));

如果可能使用字母数字键,您可以使用

echo intval(max(array_keys($array)));

echo max(array_filter(array_keys($array), 'is_int'));  
// hint taken from Amal's answer, but index calculation logic is still same as it was.

Demo

关于php - 获取 PHP 数组中的最后一个数字索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20027520/

相关文章:

arrays - 如何返回动态特征数组

php - SQL 查询转换为 codeigniter 事件记录

php - 使用未定义的常量 sql - 假定为 'sql'

php - Laravel Bootstrap 4 Modal - 在带有 AJAX 调用数据的点击事件上显示模态

c - 如何在 (int argc, char **argv) 中 printf argv

arrays - R 中的数组要替换的项目数不是替换长度的倍数

arrays - 具有最大乘积的行列或对角线

java - 返回 boolean 值数组时出现奇怪的结果

php - 使用ajax post实时验证用户名和电子邮件地址

php - 开始用于网络的 python