Page 1 of 1

Associaive array insert order & iteration

Posted: Sun Apr 12, 2009 11:46 am
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!

Re: Associaive array insert order & iteration

Posted: Sun Apr 12, 2009 1:43 pm
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"

Re: Associaive array insert order & iteration

Posted: Sun Apr 12, 2009 6:18 pm
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.