Customizing SMF > SMF Coding Discussion

Get array numeric index

(1/3) > >>

Sir Osis of Liver:
For reasons not worth mentioning, I'm creating a manual array and need the highest numeric index in the array -


--- Code: ---
$link[1] = 'aaaaaaaaaaaaaaaa';
$link[2] = 'bbbbbbbbbbbbbbbb';
$link[4] = 'ccccccccccccc';
$link[5] = 'ddddddddddddddddd';
$link[7] = 'eeeeeeeeeeeeeeee';


--- End code ---

In this example, I'm looking for '7'.  Can't use count($link) because there may be gaps in the index, as shown.  Any way to do this?


Chen Zhen:
You can use end()
ref. http://php.net/manual/en/function.end.php


--- Code: ---
$link[1] = 'aaaaaaaaaaaaaaaa';
$link[2] = 'bbbbbbbbbbbbbbbb';
$link[4] = 'ccccccccccccc';
$link[5] = 'ddddddddddddddddd';
$link[7] = 'eeeeeeeeeeeeeeee';
end($link);

$lastKey = key($link);

--- End code ---

or I suppose you can use array_pop & array_keys


--- Code: ---$link[1] = 'aaaaaaaaaaaaaaaa';
$link[2] = 'bbbbbbbbbbbbbbbb';
$link[4] = 'ccccccccccccc';
$link[5] = 'ddddddddddddddddd';
$link[7] = 'eeeeeeeeeeeeeeee';
$lastKey = array_pop(array_keys($link));

--- End code ---

.. there are many ways to do it.

Sir Osis of Liver:
That gives you the last value, I need the actual index number - [7].

Shambles:

--- Code: ---$keys = array_keys($link);
$last = end($keys);

--- End code ---

shawnb61:
If you may have numeric and non-numeric keys, I think you'll have to loop thru them & do the test the long way...

Alternatively, you could use array_filter, specify a callback that checks if the key is_int.   Then do a max() on the resulting array.

https://stackoverflow.com/questions/7947940/target-numeric-keys-only-in-array


Navigation

[0] Message Index

[#] Next page

Go to full version