Skip to content

06: Type-Safe Sorting with SortDirection

Give a leaderboard function a type-safe way to accept a sort direction. Callers choose a case from the built-in enum.

  • PHP 8.6 CLI. Confirm the version with php --version.
  • Review the previous chapter if you’re following the series in order.

Allow about 10 minutes for the walkthrough and exercise.

A runnable sort-direction.php example.

Run the following from the root of the Code with PHP repository.

Terminal window
php code/php-8-6/06-sort-direction/sort-direction.php
sort-direction.php
<?php
declare(strict_types=1);
function orderScores(array $scores, SortDirection $direction = SortDirection::Ascending): array
{
uasort($scores, static fn (int $left, int $right): int => match ($direction) {
SortDirection::Ascending => $left <=> $right,
SortDirection::Descending => $right <=> $left,
});
return $scores;
}
$scores = ['Ari' => 42, 'Jo' => 60];
echo implode(', ', array_keys(orderScores($scores))), PHP_EOL;
echo implode(', ', array_keys(orderScores($scores, SortDirection::Descending))), PHP_EOL;
Ari, Jo
Jo, Ari

The signature accepts Ascending and Descending through a shared enum type. The sample maps the case to a comparator because uasort() expects a comparator. It preserves the player names as array keys.

Add Cara with 65 points. Confirm that she appears first only in descending order.

Continue with DocComments on Function Parameters.