Maps

A key is a string; a missing key is not an empty string.

An associative array stores pairs. $map['Ann'] = 'Riga' stores a city. It is the same [] syntax as a list: the difference is in the keys. A list has dense integers from zero. A map has your own keys.

Reading a missing key gives a warning and null, not an exception. The ?? operator returns a fallback value both for null and for a missing key: $map[$name] ?? 'none'. That is a proper boundary for a function that promises a string, not null.

array_key_exists tells "there is no key" from "the key holds null". isset treats null as absence. If you care about storing null as a value, use array_key_exists. In the tasks the values are ordinary strings, so ?? is enough.

foreach ($map as $key => $value) walks the pairs. Do not change the array you are iterating with foreach by removing from it. Build a new one first. Assigning an array in PHP makes a separate copy, until you start using references with &.

Practice

  1. No key

    Which operator substitutes none if the key is missing or holds null?

    • ?:
    • ??
    • ===
    • ++
  2. Writing again

    Riga was written under the key Ann, then Rome under the same key. What does the key hold?

  3. City

    Write function city($name). The map holds only Ann => Riga. Return the city or none.