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

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.


If you are concerned, you could always pick one as the correct order and then reimplement the other function based on that. And if you care about consistency between the two calls, you probably are going to call both array_keys and array_values at the same time. So why not do both simultaneously? E.g., let's assume that the order of array_keys() is "correct". Then do:

function arrayKV($arr) {
    $keys = array_keys($arr);
    $values = array();
    foreach($keys as $key) {
        $values[] = $arr[$key];
    }
    return array('keys' => $keys, 'values' => $values);
}

That way, you know that they are in the same order. Alternatively, you could provide the keys to use as the order:

function arrayValuesStable($arr, $keys) {
    $values = array();
    foreach($keys as $key) {
        $values[] = $arr[$key];
    }
    return $values;
}

Tags:

Php