An array stores several values in a single variable. Instead of creating $fruit1, $fruit2, $fruit3, you group everything into $fruits.

Two main families

  • Indexed array: each value has a number, starting from 0. E.g. $fruits = array(“apple”, “pear”); — $fruits[0] holds “apple”.
  • Associative array: each value has a text key. E.g. $user = array(“name” => “Marie”, “age” => 30); — $user[“name”] holds “Marie”.

Going through an array

The foreach loop is made for this: it visits each element one after the other. You can grab the value alone, or the key and the value together.

  1. Add a value: $fruits[] = “cherry”;.
  2. Count: the count($fruits) function.

Key point: an array groups values, indexed by number or by key. foreach is the simplest way to go through it.