PHP

Sort PHP Arrays by Custom User-Defined Comparison Logic

Implement advanced sorting for PHP arrays using `usort()` or `uasort()` and a custom comparison function, allowing flexible ordering of complex data structures.

<?php

$users = [
    ['name' => 'Alice', 'age' => 30, 'score' => 85],
    ['name' => 'Bob', 'age' => 25, 'score' => 92],
    ['name' => 'Charlie', 'age' => 30, 'score' => 78],
    ['name' => 'David', 'age' => 22, 'score' => 92]
];

echo "Original Users:
";
print_r($users);

// Sort by age (ascending), then by score (descending)
usort($users, function($a, $b) {
    if ($a['age'] == $b['age']) {
        // If ages are equal, sort by score descending
        return $b['score'] <=> $a['score'];
    }
    // Otherwise, sort by age ascending
    return $a['age'] <=> $b['age'];
});

echo "Users Sorted by Age (asc) then Score (desc):
";
print_r($users);

$words = ['apple', 'banana', 'kiwi', 'grapefruit', 'orange'];

echo "Original Words: " . implode(', ', $words) . "
";

// Sort by string length (descending)
usort($words, function($a, $b) {
    return strlen($b) <=> strlen($a);
});

echo "Words Sorted by Length (desc): " . implode(', ', $words) . "
";

?>
How it works: The `usort()` and `uasort()` functions allow you to sort an array using a user-defined comparison function. `usort()` re-indexes the array after sorting, while `uasort()` maintains key-value associations. The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered respectively less than, equal to, or greater than the second. This provides maximum flexibility for sorting complex data structures or by multiple criteria.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs