5

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.

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

12 Comments

Max evaluates strings as 0. Interesting, didn't know that. That's helpful. I figured an option was to use array_keys. +1
Yep, max: When given a string it will be cast as an integer when comparing.
What if the array contains ("19xyz" => "value")?
The number at the beginning is taken into consideration; xyz is ignored. "19xyz" would evaluate as "19." If you have numbers at the beginning of a string and don't want it to return those, then just using max won't work for you.
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.
|
5

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!

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.