Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting last numeric index in PHP array

Tags:

arrays

php

I have a PHP array that has both a varying number of elements and varying types of associations, like so:

$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
        )

)

What I'm trying to do is get the last numerical index in these arrays and some before it. Like, in the first example, I want to get $example[18] and in the second I want to return $other[9].

I was using count($array)-1 before the named associations came into play.

like image 550
Corey Avatar asked Nov 17 '13 05:11

Corey


2 Answers

Use max and array_keys

echo max(array_keys($array));

In case of a possibility of alphanumeric keys, you can use

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

like image 83
Hanky Panky Avatar answered Sep 27 '22 19:09

Hanky Panky


If your array isn't ordered and you want to get the last numeric index, then you could use array_filter() as follows:

$numerickeys = array_filter(array_keys($example), 'is_int');
echo end($numerickeys); // => 18

Demo!

like image 30
Amal Murali Avatar answered Sep 27 '22 20:09

Amal Murali