Is foreach sorted?

philmasterplus

Active member
I. E. when I run foreach over a map with integers as keys, does it loop from the smallest to the biggest key? Similiary, does it run alphabetically over a map with strings as keys? I understand that most languages do not guarantee that foreach is iterated in a correct order, but given how ASH works...but no information in the wiki :(
 

StDoodle

Minion
In my experience at least, it iterates in the same order in which keys were added to the map. If you need a specific order, you'll need to do a sort() first.
 

Bale

Minion
If you need a specific order, you'll need to do a sort() first.

foreach will iterate over all keys in alphanumeric order. The order of a foreach is not variable by creation and that is not what sort() does.
 
Last edited:

heeheehee

Developer
Staff member
I'm fairly sure the answer is yes, it'll loop from smallest to biggest key. Strings as keys are a bit funky, as uppercase letters have priority over lowercase letters (e.g. map["Orange"] is listed before map["apple"]), but this can be explained by converting each letter to its ASCII value. Since A-Z are 71-96 or something like that, and a-z are 97-122 or so.

(sorta ninja'd)
 

slyz

Developer
Hmm. Doesn't sort my_map by value and sort my_map by index mess key => value relationships? I thought it did.

If this example isn't enough, this is what sort() does (it does mess up key => value relationship, and the key has to be an int):
PHP:
int[int]my_map;
my_map[2] = 20 ;
my_map[0] = 40 ;
my_map[1] = 30 ;
print("my_map:");
foreach i,v in my_map
   print("my_map["+i+"] = "+v);
sort my_map by value ;
print("my_map after sorting:");
foreach i,v in my_map
   print("my_map["+i+"] = "+v);
will result in:
Code:
my_map[0] = 20
my_map[1] = 30
my_map[2] = 40

Messing up the key => value relationship is the only way to actually change the order, since, as Bale pointed out, foreach will always go through the keys in the same order.
 
Last edited:
Basically, 'sort' is only useful in cases where your data exists entirely in the values of the map; the keys can have no meaning beyond simply being distinct. Typically this would imply the use of an array, or a map with sequential int keys (which has the advantage over an actual array that you don't have to know the exact size in advance).
 
Top