note 62785 deleted from control-structures.foreach by danbrown

From: Date: Tue, 28 Apr 2009 13:05:59 +0000
Subject: note 62785 deleted from control-structures.foreach by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-153911@lists.php.net to get a copy of this message
Note Submitter: php_man_resp at earthshod dot co dot uk ---- To atroxodisse: This behaviour is normal. PHP arrays are associative arrays but, unlike Perl, with artificial order maintenance. Keys can be any scalar value except references; of course integers are scalars, so traditional integer-indexed arrays just work. {You can even have fractions in array indices, as long as you enclose the index in speech marks, such as $array["1.5"]! This is not unique to PHP, by the way, but existed by accident in some dialects of BASIC seen on 1980s-vintage home computers.} The foreach loop iterates over keys in chronological order of when they were added to the array, which is *not* necessarily the same as the sort order. The print_r() function uses the same iteration order. If you want to add elements to the beginning of an existing numeric array {or between existing elements -- either using fractional indices, or because you left gaps when populating the array} and have foreach iterate over them in order, then you will need to use ksort() on the array *first*.

« previous php.notes (#153911) next »