Hanno Fietz Hanno Fietz - 1 month ago 10
PHP Question

Is the order of keys returned from array_keys the same as the order in the input array?

Given an associative array like the following,

$field_defaults = array(
'id' => 0,
'name' => 'new item',
'desc' => '',
'parent_id' => 0,
);


can I rely on
array_keys()
returning the keys in the order they were specified? Or, more precisely, since arrays in PHP seem to have a stable order, as per this answer, are the keys returned by
array_keys()
in the same order as they appear in the input array? The manual page doesn't give any hints.

When I try this, they seem to respect the original order, but I would like to be able to rely on that behaviour.

Jon Jon
Answer

TL;DR: Theoretically you can't count on it; for practical purposes IMO you can.


Since the docs do not guarantee the ordering then technically the correct answer would be "no, you can't count on that".

That's because theoretically the developers could have chosen to reserve themselves the option of changing the implementation at a future date so that it does not honor the existing order any more (perhaps to improve performance, or to gain some other benefit).

Now as a practical matter, we know that the current implementation honors the ordering -- PHP arrays are ordered containers (there is a linked list of values among other things) -- and this is something you wouldn't ever expect to change.

If it did, the change would hint to a corresponding significant change in the internal implementation of arrays and that would in turn be likely to break lots of other code too. I don't see it happening any time soon.