Skip to content
Educora
Beginner16 min4 / 10

Arrays and foreach

Create indexed, associative and multidimensional arrays, walk through them with foreach, sort them, and learn to destructure and combine arrays.

Check yourself
In this lesson you will learn
  • Create indexed, associative and multidimensional arrays and access their elements
  • Loop over arrays with foreach and use functions such as count, implode and array_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
<?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";
Expected output
Baku
4
Shaki
Array
(
    [0] => Baku
    [1] => Ganja
    [2] => Sumgait
    [3] => Shaki
)
Baku, Ganja, Sumgait, Shaki

implode 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
<?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";
}
Expected output
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
<?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";
Expected output
Aysel: 4.7
Murad: 3.7
Elvin: 5
3
Aysel, Murad, Elvin

Sorting and useful functions

PHP
<?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);
Expected output
4
14.4
7.5
bool(true)
bread, milk, cheese, tea
bread, milk, tea, cheese
cheese
Array
(
    [0] => blue
    [1] => green
    [2] => red
)
FunctionSorts byKeys
sort / rsortvalue, ascending / descendingrenumbered
asort / arsortvalue, ascending / descendingkept
ksort / krsortkey, ascending / descendingkept
usortyour own comparison function (next lesson)renumbered
All sorting functions change the array in place and do not return a new array.

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
<?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";
Expected output
gold, silver
a=2 b=1
Nigar lives in Shaki
tea + bread + soup + salad + cake
Old style
$user = array('name' => 'Aysel', 'age' => 15);
list($x, $y) = $point;
$all = array_merge($boys, $girls);
Modern PHP
$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[] = $x appends an element, and count gives the size.
  • An associative array stores key => value pairs; foreach ($arr as $key => $value) gives you both.
  • Multidimensional arrays are like tables; array_column extracts one column.
  • sort discards keys, asort and ksort keep them; sorting functions change the array in place.
  • [$a, $b] = $arr destructures an array, and [...$a, ...$b] combines arrays.

Check yourself

10 questions. Every correct answer earns XP.

1 / 10
What does $a = [10, 20, 30]; echo $a[1]; print?