PHPPHP
BeginnerLesson 6 of 16

Arrays: Lists and Maps in One – PHP

The universal PHP array, its functions and destructuring.

PHP has only one collection type: the array. It is both a list (keys 0, 1, 2 …) and a dictionary (arbitrary keys). You append with [].

<?php
$zahlen = [3, 1, 2];
$zahlen[] = 5;                  // append
sort($zahlen);                  // sorts in place
echo implode(", ", $zahlen), "\n";                              // 1, 2, 3, 5
echo count($zahlen), " ", $zahlen[0], " ", end($zahlen), "\n";  // 4 1 5

$person = ["name" => "Ada", "alter" => 36];
$person["stadt"] = "London";
echo $person["email"] ?? "none", "\n";
var_dump(array_key_exists("name", $person), in_array(2, $zahlen, true));

The array functions array_map, array_filter and array_reduce replace many loops. Note: array_filter keeps the keys.

<?php
$preise = ["Apfel" => 1.2, "Birne" => 2.0, "Kiwi" => 0.5];

$teuer = array_filter($preise, fn($p) => $p > 1);
print_r($teuer);                                  // Apfel and Birne, keys are kept

$summe = array_reduce($preise, fn($carry, $p) => $carry + $p, 0);
echo $summe, "\n";                                // 3.7

arsort($preise);                                  // descending by value, keys are kept
echo array_key_first($preise), "\n";              // Birne

Destructuring and spread make arrays pleasant to work with:

<?php
$person = ["name" => "Ada", "alter" => 36];
['name' => $n, 'alter' => $a] = $person;
[$erste, , $dritte] = [10, 20, 30];
$alle = [...[1, 2], ...[3, 4]];
echo "$n ($a), $erste, $dritte, ", count($alle), "\n";   // Ada (36), 10, 30, 4
WarningArrays are value types: $b = $a; copies the array (copy-on-write). Objects, on the other hand, are passed by handle – changes are visible everywhere.
TipDifference between sort / asort / ksort / usort: by value (renumbered) / by value (keys are kept) / by key / with a custom comparison function.