0

I have an array like this:

Array ( [2] => -100 [0] => -7.1 )

It is not ordered because if I sort this array, it will become this array into this Array ( [0] => -7.1 [1] => -100) and I am not looking for that, I just want to know the index value of an array like that....

In this case if I use the php function to know the last index it shows me 0 BUT althought it's in the last position the last index really is 2, how can I get 2 and not 0?

I am not using PHP 7, I am using PHP 5

Thanks

  • 2
    Does this answer your question? [Search for highest key/index in an array](https://stackoverflow.com/questions/6126066/search-for-highest-key-index-in-an-array) – Kaz Mar 02 '20 at 05:35

3 Answers3

1

There is the function array_key_last(). It's return the last key of an array. Here is an example (PHP 7+):

// array_key_last()  ( array $array ) : mixed

$arr = [
    '2' => 3,
    '5' => 2,
    '0' => 10
];

print_r(array_key_last($arr));

UPDATE

In PHP 7 there is no array_key_last() function, so in PHP 5 we can use end() with key(). Function end() set the pointer of array to the last element and return it. Function key() return the key of the current element of array. Example:

$arr = [
    '2' => 3,
    '5' => 2,
    '0' => 10
];

end($arr);
print_r(key($arr));
Theder
  • 59
  • 4
1

Since there is no regularity in your proposed array structure, use max(array_keys($arr)).

El_Vanja
  • 3,660
  • 4
  • 18
  • 21
0

Since you are not using PHP7, you can use count minus 1

$a = array(5, 3, 4);
print_r($a[count($a) - 1]);
Jonathan Rosa
  • 992
  • 7
  • 22