The query string

Parsing key-value pairs without superglobals.

A piece like name=Ann&city=Riga is a query string. parse_str parses it into an array. A key without a value and a repeated key follow PHP's rules: a repeat may build an array. To parse one expected key in the exercise, take $out[$key] ?? 'none' after parsing.

Do not read $_GET inside a pure function. Pass the string as an argument. Then the function can be checked without a web server, and in the service one line at the boundary reads $_SERVER['QUERY_STRING'] and calls the function. It is also easier to substitute the input in a test.

parse_str writes into the array you pass as the second argument. Without a second argument it touches variables in the current scope: old behaviour that nobody uses. Always give it your own array.

Values from a query are strings. They become numbers only after a separate check. Do not pass a raw string into SQL or a file path. This lesson only extracts the value. The next one checks it.

Practice

  1. Where the query comes from

    Where should a pure function get the query string from?

    • From $_GET inside the function
    • From an argument
    • From the file /etc/passwd
    • From echo
  2. A pair

    In the string name=Ann&city=Riga, what is the value of the key city?

  3. Get a parameter

    Write function query_value($query, $key). Parse the query string and return the key's value or none.