- Create indexed, associative and multidimensional arrays and access their elements
- Loop over arrays with
foreachand use functions such ascount,implodeandarray_column - Sort arrays, destructure them and combine them with
...
A class has 25 students, and you need to store each one's marks. Create 25 separate variables? Of course not. This is where an array helps — a structure that keeps many values under one name. In PHP an array works both as a list and as a dictionary, so you will find it in almost every script.
Indexed arrays
An array is created with square brackets: ["Baku", "Ganja"]. Its elements are numbered with indexes starting from 0. $cities[] = ... adds a new element to the end, count returns the number of elements, and print_r shows the whole contents of the array.
<?php
$cities = ["Baku", "Ganja", "Sumgait"];
$cities[] = "Shaki";
echo $cities[0], "\n";
echo count($cities), "\n";
echo $cities[count($cities) - 1], "\n";
print_r($cities);
echo implode(", ", $cities), "\n";Baku
4
Shaki
Array
(
[0] => Baku
[1] => Ganja
[2] => Sumgait
[3] => Shaki
)
Baku, Ganja, Sumgait, Shakiimplode joins the elements of an array into one string with the given separator, and explode does the opposite: it splits a string into an array at the separator. If you access an index that does not exist, PHP 8 shows an Undefined array key warning and returns null.
Associative arrays and foreach
An associative array uses meaningful keys instead of numbers: "name" => "Leyla". It is handy for storing information about one thing. The **foreach** loop visits every element of an array: foreach ($arr as $value) gives only the values, while foreach ($arr as $key => $value) gives the keys as well. You check whether a key exists with isset or array_key_exists.
<?php
$student = [
"name" => "Leyla",
"age" => 14,
"city" => "Baku",
];
$student["grade"] = 8;
echo "{$student['name']} is {$student['age']} years old\n";
var_dump(isset($student["email"]));
var_dump(array_key_exists("city", $student));
foreach ($student as $key => $value) {
echo "$key: $value\n";
}Leyla is 14 years old bool(false) bool(true) name: Leyla age: 14 city: Baku grade: 8
Multidimensional arrays
An element of an array can be another array. Results from a database usually look exactly like this: a list of rows, where each row is an associative array. array_column takes one column out of all the rows.
<?php
$students = [
["name" => "Aysel", "marks" => [5, 4, 5]],
["name" => "Murad", "marks" => [4, 4, 3]],
["name" => "Elvin", "marks" => [5, 5, 5]],
];
foreach ($students as $student) {
$avg = array_sum($student["marks"]) / count($student["marks"]);
echo $student["name"] . ": " . round($avg, 1) . "\n";
}
echo $students[1]["marks"][2], "\n";
echo implode(", ", array_column($students, "name")), "\n";Aysel: 4.7 Murad: 3.7 Elvin: 5 3 Aysel, Murad, Elvin
Sorting and useful functions
<?php
$prices = ["bread" => 0.8, "milk" => 1.9, "cheese" => 7.5, "tea" => 4.2];
echo count($prices), "\n";
echo array_sum($prices), "\n";
echo max($prices), "\n";
var_dump(in_array(1.9, $prices));
echo implode(", ", array_keys($prices)), "\n";
asort($prices);
echo implode(", ", array_keys($prices)), "\n";
arsort($prices);
echo array_key_first($prices), "\n";
$colors = explode(",", "red,green,blue");
sort($colors);
print_r($colors);4
14.4
7.5
bool(true)
bread, milk, cheese, tea
bread, milk, tea, cheese
cheese
Array
(
[0] => blue
[1] => green
[2] => red
)| Function | Sorts by | Keys |
|---|---|---|
sort / rsort | value, ascending / descending | renumbered |
asort / arsort | value, ascending / descending | kept |
ksort / krsort | key, ascending / descending | kept |
usort | your own comparison function (next lesson) | renumbered |
Destructuring and spreading
You can write the elements of an array into separate variables in one line: [$a, $b] = $pair; — this is called destructuring. For an associative array you name the keys. The spread operator ... “pours” the elements of one array into another.
<?php
[$first, $second] = ["gold", "silver"];
echo "$first, $second\n";
$a = 1;
$b = 2;
[$a, $b] = [$b, $a];
echo "a=$a b=$b\n";
["name" => $name, "city" => $city] = ["name" => "Nigar", "city" => "Shaki"];
echo "$name lives in $city\n";
$morning = ["tea", "bread"];
$evening = ["soup", "salad"];
$menu = [...$morning, ...$evening, "cake"];
echo implode(" + ", $menu), "\n";gold, silver a=2 b=1 Nigar lives in Shaki tea + bread + soup + salad + cake
$user = array('name' => 'Aysel', 'age' => 15);
list($x, $y) = $point;
$all = array_merge($boys, $girls);$user = ['name' => 'Aysel', 'age' => 15];
[$x, $y] = $point;
$all = [...$boys, ...$girls];array() and list() still work, but in new code the short [] syntax is the standard.Key points
- Elements of an indexed array are numbered from 0;
$arr[] = $xappends an element, andcountgives the size. - An associative array stores
key => valuepairs;foreach ($arr as $key => $value)gives you both. - Multidimensional arrays are like tables;
array_columnextracts one column. sortdiscards keys,asortandksortkeep them; sorting functions change the array in place.[$a, $b] = $arrdestructures an array, and[...$a, ...$b]combines arrays.
Check yourself
10 questions. Every correct answer earns XP.
$a = [10, 20, 30]; echo $a[1]; print?