5.5. Keys and Values

A list of the keys may be obtained using the keys() efun. For example:

Example 5-11. Calling keys() on a mapping

  mixed *idx;
  mapping x;

  x = ([ "x" : 3, "y" : 4]);
  idx = keys(x);

  // idx = ({ "x", "y" })

Note that keys() will return the list of keys in a seemingly random order. The actual order of the keys is an effect of how mappings are implemented in the driver. Do NOT rely upon the fact that the order of the keys has anything to do with the order you inserted them, deleted them, or any other natural ordering.

A list of the values in a mapping may be obtained using the values() efun. For example:

Example 5-12. Calling values() on a mapping

  mixed *vs;
  mapping x;

  x = ([ "x" : 3, "y" : 4]);
  vs = values(x);

  // vs = ({ 3, 4 });

Similarly, values are not sorted in any natural way either. However, the roder of the values will be the same as the order of their corresponding keys.

The key/value pairs in a mapping may be iterated over using the each() efun. each() returns an empty array when the end of the mapping is reached. For example:

  mixed *pair;

  while ((pair = each(x)) != ({ })) {
    write("key   = " + pair[0] + "\n");
    write("value = " + pair[1] + "\n");

An easier to read and safer way to do the same thing is to use the foreach statement:

Example 5-13. Using foreach on a mapping

  mapping m = ([ "i": 1, "iv": 4, "v": 5 ]);

  foreach (string k, int v in m) {
    write(sprintf("key: %s value: %d\n", k, v));

Using foreach is easier to read because you know what the types of the keys and values at that point should be and you can explicitly refer to them using distinct and readable variable names.