Store several values in indexed or associative arrays and manipulate them with PHP’s essential functions.
Open this lesson in KodokonAn 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
$colors = ["red", "green", "blue"];
echo $colors[0];
echo $colors[2];
$colors[] = "yellow";
$colors[1] = "purple";
echo count($colors);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
$user = [
"name" => "Awa",
"age" => 28,
"city" => "Lyon",
];
echo $user["name"];
echo $user["city"];
$user["age"] = 29;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
$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);$user = ["city" => "Lyon"], how do you read the value “Lyon”?$user->city$user["city"]$user.citycount($colors) return?