Associaive array insert order & iteration

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
bfcam
Forum Newbie
Posts: 1
Joined: Sun Apr 12, 2009 11:39 am

Associaive array insert order & iteration

Post by bfcam »

Easy n00b question here:

Does the iteration order of an Associative array always match the insertion order?

For example:

Code: Select all

 
$name = array('jim' => 'smith', 'bob' => 'jones', 'tom' => 'baker');
foreach($name as $first => $last) {
  print "$first $last\n";
}
 
Am I always guaranteed to see?
jim smith
bob jones
tom baker

Thanks!
Mark Baker
Forum Regular
Posts: 710
Joined: Thu Oct 30, 2008 6:24 pm

Re: Associaive array insert order & iteration

Post by Mark Baker »

bfcam wrote:Does the iteration order of an Associative array always match the insertion order?
Unless you do something to change that order, such as sort(), then "yes"
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: Associaive array insert order & iteration

Post by Chris Corbyn »

Yeah PHP has no unordered lists. If you want to compare two array for equality, regardless of the ordering you need to grab the array_values() for each array, sort() those values and the compare for equality with the "==" operator.
Post Reply