Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
645 views
in Technique[技术] by (71.8m points)

php - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...