Thuta Learning
PHP
BasicProgrammingBeginner

Arrays

PHPLesson 930 min

What you'll walk away with

  • Write indexed and associative arrays and explain why both are the same array type
  • Read a possibly missing key safely with ?? and isset()
  • Predict which keys array_map() and array_filter() keep, and order data with usort()
  • Use the spread operator (...) and destructuring ([$a, $b] = ...)

Explain it simply

Explain it simply

An array is a row of slots that holds many values in a single variable. Every slot has a number or a name (the key), and you use that key to get the value back. Menus, product lists, user profiles and cart items are all kept in arrays.

Other languages split this into a list and a dictionary; PHP does both with a single array type. With numbers it behaves like a list and with names it behaves like a dictionary, so it pays to understand the rules that make it work.

Problem → Why → Solution

The problem: removing one item breaks the loop

Remove "Courses" from a menu array with unset() and print the rest with a for loop. Only three items remain, so count() gives 3, but key 1 is gone and key 3 is never reached, so "Contact" is skipped and a warning appears.

menu.php
<?php
$menu = ["Home", "Courses", "Blog", "Contact"];
unset($menu[1]);                    // remove "Courses"

for ($i = 0; $i < count($menu); $i++) {
    echo $menu[$i] . PHP_EOL;       // key 1 no longer exists; key 3 is never reached
}

Why does this happen?

A PHP array is a map from keys to values, not a numbered row. unset($menu[1]) deletes key 1 and does not renumber the others (0, 2 and 3 remain). To visit every element use foreach, and call array_values() when you want consecutive numbers back.

Core concept: an array is an ordered map

Despite its name, a PHP array is an ordered map: key => value pairs that remember the order you added them. Keys can be integers or strings. When you write ['HTML', 'CSS', 'PHP'] PHP assigns the keys 0, 1, 2 for you, and we call that an indexed array. When you choose the keys yourself, ['name' => 'Mya Mya'], it is an associative array. There is only one array type, so you can even mix both styles in one array.

Because arrays are maps, keys follow a few rules. An integer-like string key such as '1' becomes the int 1, true becomes 1 and null becomes ''. A float key is truncated, with a deprecation message when decimals are lost. Writing $list[] = 'x' appends using the next free integer key (the largest int key plus one). unset($list[1]) removes a key but never renumbers the others, so gaps appear. Reading a missing key produces Warning: Undefined array key and gives null, so use isset(), the ?? operator or array_key_exists() when a key may be absent.

Arrays are values, not shared objects. $b = $a makes an independent copy (PHP copies lazily, only when one of them changes), so changing $b never affects $a. A function that receives an array also works on its own copy unless you pass it by reference with &.

Built-in functions do most of the work. To inspect, use count(), in_array(), array_key_exists() and array_search(). To transform, array_map() returns a new array of changed values and array_filter() keeps the elements for which the callback returns true, with their original keys. To order, sort() and usort() change the array you pass in place and return true. Remember that in_array() compares loosely unless you pass true as the third argument.

Mental model: slots addressed by key
  1. Keys and values stay in order
  2. Look up a value by its key
  3. map/filter return a NEW array
  4. sort() changes the array in place

Copying an array copies its values; afterwards the two arrays are independent.

General pattern

php
<?php
$list = [value1, value2, value3];            // indexed: keys 0, 1, 2
$map = ["key" => value, "other" => value];   // associative
$list[] = $newValue;                         // append with the next integer key
$found = $map["key"] ?? $default;            // safe read of a maybe-missing key
foreach ($map as $key => $value) { /* ... */ }
$doubled = array_map(fn($x) => $x * 2, $list);
$kept = array_filter($list, fn($x) => $x > 1);   // original keys survive
sort($list);                                 // changes $list itself

Values go between [ ] separated by commas, and the key => value form makes it associative. $list[] = ... appends at the end. ?? supplies a default when the key is missing, so no warning appears.

Example: a skills list and a user profile

The first half builds an indexed array, appends one more item and reads index 2. The second half builds a user profile as an associative array, adds a new key and uses foreach to print each key with its value.

skills-and-user.php
<?php
// Indexed array: keys are 0, 1, 2 ...
$skills = ["HTML", "CSS", "PHP"];
$skills[] = "JavaScript";
echo $skills[2] . PHP_EOL;
echo count($skills) . PHP_EOL;

// Associative array: keys are names you choose
$user = [
    "name" => "Mya Mya",
    "role" => "Student",
];
$user["city"] = "Mandalay";
echo $user["name"] . " is a " . $user["role"] . PHP_EOL;

foreach ($user as $key => $value) {
    echo "$key: $value" . PHP_EOL;
}

Code breakdown

  1. Line 3$skills = ["HTML", "CSS", "PHP"];

    No keys are given, so PHP assigns 0, 1 and 2 itself. This is an indexed array.

  2. Line 4$skills[] = "JavaScript";

    Empty brackets append at the end under key 3, so count() returns 4.

  3. Line 5echo $skills[2] . PHP_EOL;

    Indexes start at 0, so [2] is the third item, PHP. [3] would be JavaScript.

  4. Line 10"name" => "Mya Mya",

    => ties a key to a value. PHP allows a trailing comma after the last item, which keeps diffs clean when you add another one.

  5. Line 13$user["city"] = "Mandalay";

    Assigning to a key that does not exist yet adds it; assigning to an existing key replaces its value.

  6. Line 16foreach ($user as $key => $value) {

    foreach hands over every item in insertion order with both key and value. It is the safest loop because you never compute indexes yourself.

You should see
PHP
4
Mya Mya is a Student
name: Mya Mya
role: Student
city: Mandalay

Missing keys, gaps and safe reads

The ?? operator uses its right-hand default when the key is missing or the value is null, and it raises no warning. isset() also treats a null value as not set. If you only want to know whether the key exists, even with a null value, use array_key_exists(). After unset(), call array_values() when you need consecutive numbers again.

safe-reads.php
<?php
$user = ["name" => "Mya Mya", "nickname" => null];

echo ($user["city"] ?? "unknown") . PHP_EOL;      // unknown, no warning
var_dump(isset($user["nickname"]));               // bool(false): null counts as unset
var_dump(array_key_exists("nickname", $user));    // bool(true): the key is there

$menu = ["Home", "Courses", "Blog"];
unset($menu[1]);
echo implode(",", array_keys($menu)) . PHP_EOL;   // 0,2
$menu = array_values($menu);
echo implode(",", array_keys($menu)) . PHP_EOL;   // 0,1

array_map, array_filter and usort

array_map() transforms every element with a callback and returns a new array. array_filter() drops some elements but keeps the original keys of the rest, so gaps such as [0, 1, 3] can remain; renumber with array_values(). usort() orders with your own callback, and the $a <=> $b form is ideal because it returns -1, 0 or 1.

map-filter-sort.php
<?php
$prices = [1200, 4500, 800, 3000];

$withTax = array_map(fn(int $p): int => (int) round($p * 1.05), $prices);
echo implode(", ", $withTax) . PHP_EOL;

$expensive = array_filter($prices, fn(int $p): bool => $p >= 1200);
echo implode(", ", array_keys($expensive)) . PHP_EOL;     // keys survive: 0, 1, 3
$list = array_values($expensive);
echo implode(", ", array_keys($list)) . PHP_EOL;          // renumbered: 0, 1, 2

$people = [
    ["name" => "Zaw", "age" => 30],
    ["name" => "Aye", "age" => 25],
    ["name" => "Mya", "age" => 35],
];
usort($people, fn(array $a, array $b): int => $a["age"] <=> $b["age"]);
echo implode(", ", array_column($people, "name")) . PHP_EOL;

$ok = sort($prices);
var_dump($ok);                       // sort() returns true, not the array
echo implode(", ", $prices) . PHP_EOL;
FunctionOrders byKeys afterwards
sort() / rsort()valuerenumbered
asort() / arsort()valuekept
ksort() / krsort()keykept
usort()your callbackrenumbered
uasort()your callbackkept

Spread and destructuring

The spread operator ... unpacks one array into another. Arrays with string keys can be spread too in PHP 8.1 and later, and a later key replaces an earlier one. Destructuring pulls an array apart into variables in one statement, and [$a, $b] = [$b, $a] swaps two values without a temporary variable.

spread-destructure.php
<?php
$first = ["HTML", "CSS"];
$second = ["PHP", "SQL"];
$all = [...$first, ...$second, "Git"];
echo implode(", ", $all) . PHP_EOL;

$defaults = ["theme" => "light", "lang" => "en"];
$custom = ["lang" => "my"];
$settings = [...$defaults, ...$custom];        // later keys win
echo $settings["theme"] . " " . $settings["lang"] . PHP_EOL;

["name" => $name, "role" => $role] = ["name" => "Mya Mya", "role" => "Student"];
echo "$name ($role)" . PHP_EOL;

[$a, [$b, $c]] = [1, [2, 3]];                  // nested
echo "$a$b$c" . PHP_EOL;
[, , $third] = ["x", "y", "z"];                // skip positions
echo $third . PHP_EOL;

$x = 10;
$y = 20;
[$x, $y] = [$y, $x];                           // swap
echo "$x $y" . PHP_EOL;

$team = [["n" => "Aye", "age" => 25], ["n" => "Zaw", "age" => 30]];
foreach ($team as ["n" => $n, "age" => $age]) {    // destructure inside foreach
    echo "$n is $age" . PHP_EOL;
}

In real projects

Where this shows up in real projects

In every PHP application the array is the basic shape of data. $_GET and $_POST are arrays, PDO's fetchAll() returns each database row as an associative array, json_decode($json, true) turns JSON into an array, and many config files simply return one. Shopping carts, menus and lists of form fields are arrays too.

Knowing about keys matters when you write APIs. json_encode() turns a consecutively numbered array into a JSON list [..] but an array with gaps into an object {"1":..}, so forgetting array_values() after array_filter() can break the frontend. Also, a function that receives an array edits its own copy, so the original data stays safe; you can use that to write helpers that return a freshly sorted array.

Common mistakes

Common mistakes

1. Using an index loop after unset() or array_filter()

for ($i = 0; $i < count($a); $i++) skips items and raises Undefined array key when the keys have gaps. Use foreach, or renumber with array_values().

2. Reading a key that may not exist

echo $user['city']; prints Warning: Undefined array key "city" and yields null when the key is missing. Write $user['city'] ?? 'unknown', or test with isset() first.

3. Expecting sort() to return the sorted array

$sorted = sort($names); stores true in $sorted, while the sorted array lives in $names itself. Call sort($names); and keep using $names, or copy the array first when you must keep the original order.

4. Calling in_array() without strict mode

in_array('1', [1, 2, 3]) returns true because the comparison is loose, and so does in_array('1e1', ['10']). When the type must match too, pass true as the third argument: in_array($x, $list, true).

Best practices

Best practices

  • Prefer foreach for walking an array, and use an index loop only when you are sure the keys are consecutive.
  • Read data that may lack keys (forms, JSON, config) with ?? every time.
  • When you send a filtered array out as JSON, remember array_values().

Mini challenge

Mini challenge: a class scoreboard

Write three functions that filter the students who passed, order them by score and compute the average. ranking() must leave the array it receives untouched.

  • passed(array $students, int $mark): array — return the names of students with a score of $mark or more as a list with keys 0, 1, 2
  • ranking(array $students): array — return a new array ordered from the highest score using usort()
  • average(array $students): float — the mean of all scores
  • After calling ranking(), print the first student of the original $class to show it did not change
scoreboard.php
<?php
function passed(array $students, int $mark): array
{
    // TODO: array_filter() the students, then array_column() the names
}

function ranking(array $students): array
{
    // TODO: usort() with $b["score"] <=> $a["score"], then return the array
}

function average(array $students): float
{
    // TODO: array_sum() of the scores divided by count()
}

// TODO: build $class with four students and print every result

Expected: Expected output: Passed: Zaw, Aye, Kyaw Top: Aye (91) First in original list: Zaw Average: 76.5

Show hint

array_column($students, 'score') pulls every score into one array. Notice that usort($students, ...) inside the function sorts its own copy and never touches the caller's array.

Show solution
scoreboard.php
<?php
function passed(array $students, int $mark): array
{
    $winners = array_filter($students, fn(array $s): bool => $s["score"] >= $mark);
    return array_column($winners, "name");
}

function ranking(array $students): array
{
    usort($students, fn(array $a, array $b): int => $b["score"] <=> $a["score"]);
    return $students;
}

function average(array $students): float
{
    return array_sum(array_column($students, "score")) / count($students);
}

$class = [
    ["name" => "Zaw", "score" => 72],
    ["name" => "Aye", "score" => 91],
    ["name" => "Mya", "score" => 58],
    ["name" => "Kyaw", "score" => 85],
];

echo "Passed: " . implode(", ", passed($class, 70)) . PHP_EOL;
$top = ranking($class);
echo "Top: " . $top[0]["name"] . " (" . $top[0]["score"] . ")" . PHP_EOL;
echo "First in original list: " . $class[0]["name"] . PHP_EOL;
echo "Average: " . number_format(average($class), 1) . PHP_EOL;

Quick quiz 1 / 3

$a = [1, 2, 3, 4, 5, 6]; $even = array_filter($a, fn($n) => $n % 2 === 0); echo implode(',', array_keys($even)); prints what?

Quick quiz 2 / 3

$a = [1, 2, 3]; $b = $a; $b[] = 99; echo count($a); prints what?

Quick quiz 3 / 3

$names = ['b', 'a']; $sorted = sort($names); var_dump($sorted); outputs what?

What to remember

  • A PHP array is a single ordered-map type: without keys it is indexed (0, 1, 2), with keys it is associative.
  • unset() does not renumber keys, so read maybe-missing keys with ?? and walk arrays with foreach.
  • array_map() returns a new array and array_filter() keeps the original keys, while sort() and usort() change the array itself.
  • Assigning an array or passing it to a function copies it, and spread and destructuring unpack data in and out.

PHP Language Reference — PHP Documentation Group

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Arrays | Thuta Learning