Arrays and sorting

Lists and associative arrays, the array functions you use most, and the sort functions.

Runs in Zerethon IDE · PHP 8.4 Official PHP documentation ↗
main.php
<?php

$scores = [70, 95, 8, 82];
$scores[] = 60;
sort($scores);
echo implode(' ', $scores), ' | count ', count($scores), "\n";

$big = array_filter($scores, fn ($s) => $s >= 80);
echo implode(',', array_map(fn ($s) => $s / 10, $big)), ' ', in_array(95, $scores, true) ? 'has 95' : 'no 95', "\n";

$ages = ['ada' => 36, 'alan' => 41];
$ages['grace'] = 85;
arsort($ages);                       // by value, high to low, keys kept
echo json_encode($ages), ' ', $ages['linus'] ?? 'unknown', ' ', array_key_exists('ada', $ages) ? 'yes' : 'no', "\n";

$people = [['name' => 'bob', 'age' => 31], ['name' => 'amy', 'age' => 25]];
usort($people, fn ($a, $b) => $a['age'] <=> $b['age']);
echo implode(', ', array_column($people, 'name')), "\n";

Output

8 60 70 82 95 | count 5
8.2,9.5 has 95
{"grace":85,"alan":41,"ada":36} unknown yes
amy, bob
  • Sort functions change the array in place and return true: sort/rsort (values, keys renumbered), asort/arsort (values, keys kept), ksort (by key), usort (your own comparison with <=>).
  • $array["missing"] gives a warning and null; use $array["key"] ?? $default or array_key_exists.
  • Pass true to in_array / array_search for a strict (===) search.