Kodokon kodokon.com

Arrays: lists and key-value pairs

Store several values in indexed or associative arrays and manipulate them with PHP’s essential functions.

8 min · 3 questions

Open this lesson in Kodokon

An array is a variable able to hold several values at once, like a shelf with multiple slots. In an indexed array, each slot is numbered by an index that starts at 0: the first element is therefore $colors[0]. You create an array with brackets [...], read a slot with $colors[index], and the syntax $colors[] = ... adds a new value at the end.

PHP
<?php

$colors = ["red", "green", "blue"];

echo $colors[0];
echo $colors[2];

$colors[] = "yellow";
$colors[1] = "purple";

echo count($colors);
Read, append, modify: the count is 4.

Sometimes a number means nothing: to describe a person, labels are better. The associative array links a key (a name, often a string) to a value, with the arrow => that reads “corresponds to”. You then access a value by its key: $user["name"]. It’s PHP’s go-to structure for representing data.

PHP
<?php

$user = [
    "name" => "Awa",
    "age" => 28,
    "city" => "Lyon",
];

echo $user["name"];
echo $user["city"];

$user["age"] = 29;
Each key leads to its value, like a mini dictionary.

PHP provides hundreds of ready-to-use array functions. Remember the essential ones: count($array) returns the number of elements; in_array($value, $array) answers true if the value is present; sort($array) sorts the array in place, from smallest to largest; implode($glue, $array) joins all elements into a single string, separated by the text of your choice; and array_keys($array) returns the list of keys.

PHP
<?php

$numbers = [8, 3, 5];
sort($numbers);

echo implode(" - ", $numbers);
echo "<br>";

$guests = ["Awa", "Bruno", "Chloe"];

if (in_array("Bruno", $guests)) {
    echo "Bruno is on the list.<br>";
}

echo count($guests);
Displays 3 - 5 - 8, then checks and counts the guests.

Knowledge check

Make sure you remember the key points of this lesson.

  1. What is the index of the first element of an indexed array?
    • 0
    • 1
    • -1
  2. With $user = ["city" => "Lyon"], how do you read the value “Lyon”?
    • $user->city
    • $user["city"]
    • $user.city
  3. What does count($colors) return?
    • The last element of the array
    • The number of elements in the array
    • The sum of the array values