PHP

Custom Sorting an Array of Objects by Key

Sort a PHP array of associative arrays or objects based on a specific key's value using the flexible `usort` function and a custom comparison.

<?php
$employees = [
    ['name' => 'Alice', 'salary' => 60000, 'age' => 30],
    ['name' => 'Bob', 'salary' => 75000, 'age' => 25],
    ['name' => 'Charlie', 'salary' => 50000, 'age' => 35],
    ['name' => 'David', 'salary' => 75000, 'age' => 28],
];

// Sort by salary in descending order, then by age in ascending order for ties
usort($employees, function($a, $b) {
    // Sort by salary descending
    if ($a['salary'] == $b['salary']) {
        // If salaries are equal, sort by age ascending
        return $a['age'] <=> $b['age'];
    }
    return $b['salary'] <=> $a['salary']; // Descending salary
});

print_r($employees);

// Sort by name alphabetically (ascending)
$fruits = ['apple', 'orange', 'banana', 'grape'];
usort($fruits, function($a, $b) {
    return strcmp($a, $b); // Ascending alphabetical
});

print_r($fruits);
?>
How it works: `usort()` allows you to sort an array by values using a user-defined comparison function. This is particularly powerful for complex data structures like arrays of associative arrays or objects, where you need to sort based on specific keys or multiple criteria. The comparison function should return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Need help integrating this into your project?

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

Hire DigitalCodeLabs