Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question

3 Answers 3

up vote 3 down vote accepted

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

share|improve this answer
    
Max evaluates strings as 0. Interesting, didn't know that. That's helpful. I figured an option was to use array_keys. +1 –  JaidynReiman Nov 17 '13 at 5:26
    
Yep, max: When given a string it will be cast as an integer when comparing. –  Hanky 웃 Panky Nov 17 '13 at 5:26
1  
What if the array contains ("19xyz" => "value")? –  ring0 Nov 17 '13 at 5:27
    
ring0 see the demo –  Hanky 웃 Panky Nov 17 '13 at 5:27
1  
This would fail if the array keys aren't ordered. @Corey: you should make it clear whether you need exactly the last numeric key's value or the greatest numeric key's value. –  Amal Murali Nov 17 '13 at 5:34

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!

share|improve this answer

This one will always work as expected:

var_dump(max(array_filter(array_keys($example), 'is_int'))); # int(18)
var_dump(max(array_filter(array_keys($other), 'is_int'))); # int(9)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.