Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does php conserve order in associative array? [duplicate]

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?

like image 703
Suzan Cioc Avatar asked Jul 14 '12 21:07

Suzan Cioc


2 Answers

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

like image 151
phihag Avatar answered Sep 27 '22 16:09

phihag


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.

like image 30
goat Avatar answered Sep 27 '22 15:09

goat