Possible Duplicate:
Are PHP Associative Arrays ordered?
If I add items to associative array with different keys, does order of addition conserved? How can I access "previous" and "next" elements of given element?
Yes, php arrays have an implicit order. Use reset
, next
, prev
and current
- or just a foreach
loop - to inspect it.
Yes, it does preserve the order. you can think of php arrays as ordered hash maps.
You can think of the elements as being ordered by "index creation time". For example
$a = array();
$a['x'] = 1;
$a['y'] = 1;
var_dump($a); // x, y
$a = array();
$a['x'] = 1;
$a['y'] = 1;
$a['x'] = 2;
var_dump($a); // still x, y even though we changed the value associated with the x index.
$a = array();
$a['x'] = 1;
$a['y'] = 1;
unset($a['x']);
$a['x'] = 1;
var_dump($a); // y, x now! we deleted the 'x' index, so its position was discarded, and then recreated
To summarize, if you're adding an entry where a key doesnt currently exist in the array, the position of the entry will be the end of the list. If you're updating an entry for an existing key, the position is unchanged.
foreach loops over arrays using the natural order demonstrated above. You can also use next() current() prev() reset() and friends, if you like, although they're rarely used since foreach was introduced into the language.
also, print_r() and var_dump() output their results using the natural array order too.
If you're familiar with java, LinkedHashMap is the most similar data structure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With