Does php support ordering in associative array?

Possible duplicate:
Are PHP associative arrays adjusted?

If I add elements to an associative array with different keys, is the order of addition preserved? How can I access the "previous" and "next" elements of this element?

+6
source share
2 answers

Yes, php arrays have an implicit order. Use reset , next , prev and current - or just a foreach loop - check it out.

+12
source

Yes, he saves the order. you can think of php arrays as ordered hash maps .

You may think that items are ordered by "index creation time". for instance

 $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 add a record that currently does not have a key in the array, the position of the record will be at the end of the list. If you update an entry for an existing key, the position does not change.

foreach iterates over arrays using the natural order shown above. You can also use next () current () prev () reset () and friends if you want, although they are rarely used since foreach was introduced into the language.

also print_r () and var_dump () output their results using the order of the natural array.

If you are familiar with java, LinkedHashMap is the most similar data structure.

+9
source

Source: https://habr.com/ru/post/920503/


All Articles