PHP

Custom Sorting PHP Arrays with usort

Learn to sort PHP arrays containing complex elements (e.g., objects or associative arrays) based on custom comparison logic using the powerful usort() function for precise ordering.

<?php

$people = [
    ['name' => 'Charlie', 'age' => 30],
    ['name' => 'Alice', 'age' => 25],
    ['name' => 'Bob', 'age' => 35]
];

// Sort by age in ascending order
usort($people, function($a, $b) {
    return $a['age'] <=> $b['age']; // PHP 7+ spaceship operator
    // For PHP < 7, use: 
    // if ($a['age'] == $b['age']) return 0;
    // return ($a['age'] < $b['age']) ? -1 : 1;
});

echo "Sorted by Age (Ascending):
";
print_r($people);
/*
Expected output:
Sorted by Age (Ascending):
Array
(
    [0] => Array
        (
            [name] => Alice
            [age] => 25
        )

    [1] => Array
        (
            [name] => Charlie
            [age] => 30
        )

    [2] => Array
        (
            [name] => Bob
            [age] => 35
        )

)
*/

// Sort by name in alphabetical order
usort($people, function($a, $b) {
    return strcmp($a['name'], $b['name']);
});

echo "
Sorted by Name (Alphabetical):
";
print_r($people);
/*
Expected output:

Sorted by Name (Alphabetical):
Array
(
    [0] => Array
        (
            [name] => Alice
            [age] => 25
        )

    [1] => Array
        (
            [name] => Bob
            [age] => 35
        )

    [2] => Array
        (
            [name] => Charlie
            [age] => 30
        )

)
*/

?>
How it works: The `usort()` function sorts an array by values using a user-defined comparison function. The callback function takes two arguments (`$a` and `$b`) representing elements being compared and must return an integer less than, equal to, or greater than zero if `$a` is considered to be respectively less than, equal to, or greater than `$b`. This is essential for sorting complex data structures like arrays of objects or associative arrays based on specific keys or custom logic.

Need help integrating this into your project?

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

Hire DigitalCodeLabs