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.
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
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With