PHP: Data structures – code examples
Contents
Working with Arrays as a List
Use case: Manage collections of values: add, sort, filter, convert.
<?php
$zahlen = [5, 3, 8, 1];
$zahlen[] = 10;
sort($zahlen);
echo implode(", ", $zahlen), "\n";
$doppelt = array_map(fn($z) => $z * 2, array_filter($zahlen, fn($z) => $z > 3));
echo implode(", ", $doppelt), "\n";
echo array_sum($zahlen), " ", max($zahlen), " ", count($zahlen), "\n";PHP has no list literal with comprehension: array_filter and array_map (with arrow functions) do the same. Output: 1, 3, 5, 8, 10, then 10, 16, 20, then 27 10 5.
Associative Array (Map)
Use case: Store mappings, e.g. configurations, database rows or JSON-like data.
<?php
$person = ["name" => "Ada", "alter" => 36];
$person["stadt"] = "London";
foreach ($person as $schluessel => $wert) {
echo "$schluessel = $wert\n";
}
echo $person["email"] ?? "no email", "\n";In PHP the map is the same thing as the normal array. ?? returns a default value if the key is missing – without a warning.
Sorting with usort and <=>
Data structures#usort#sort#spaceship#array_column
Use case: Order records by a field, e.g. users by age or products by price.
<?php
$nutzer = [
["name" => "Ada", "alter" => 36],
["name" => "Bob", "alter" => 25],
["name" => "Cy", "alter" => 36],
];
usort($nutzer, fn($a, $b) => [$b["alter"], $a["name"]] <=> [$a["alter"], $b["name"]]);
echo implode(", ", array_column($nutzer, "name")), "\n";<=> also compares arrays element by element: this is how you sort by several criteria (age descending, name ascending). Result: Ada, Cy, Bob.
array_column and Grouping
Data structures#array_column#grouping#json_encode
Use case: Prepare database rows: extract a column, index by ID or group.
<?php
$zeilen = [
["id" => 1, "name" => "Coffee", "kat" => "Beverage"],
["id" => 2, "name" => "Tea", "kat" => "Beverage"],
["id" => 3, "name" => "Cookie", "kat" => "Snack"],
];
$namen = array_column($zeilen, "name"); // list of names
$nachId = array_column($zeilen, null, "id"); // key = id
$gruppen = [];
foreach ($zeilen as $z) {
$gruppen[$z["kat"]][] = $z["name"];
}
echo implode(",", $namen), " | ", $nachId[3]["name"], " | ", json_encode($gruppen, JSON_UNESCAPED_UNICODE), "\n";array_column is the quick way to turn result rows into a single column or an array indexed by ID. Grouping works with $gruppen[$key][] = ....