Lists

Indexes start at zero; better not to leave gaps.

A list in PHP is an array with the keys 0, 1, 2. [] appends an element to the end. $items[0] reads the first one. Reading a non-existent index in modern PHP gives a warning. Do not use the warning as a way to ask "does the key exist".

count($items) is the length. implode(',', $items) joins the values. explode(',', $text) cuts the string back up. An empty string through explode gives an array with one empty string, not an empty array. That is a common surprise on an empty form field.

Array functions do not always change the original array. array_reverse returns a new one. sort changes the array itself and renumbers the keys. For a map, sort destroys the keys: you need asort there if you sort by value.

Keep lists dense. An array with the keys 0 and 2 is already almost a map. implode will join its values, but a loop over "every index up to count" runs into the gap. If gaps have appeared, it is a map and should be read by key.

Practice

  1. The first index

    What index does the first element of a list built with [] have?

    • 0
    • 1
    • -1
    • null
  2. Joining

    What string does implode(',', ['go', 'java']) produce?

  3. Two words

    Write function join_two($a, $b). Return the words separated by a comma with no space, in the order given.