PHP

Sort Associative Array by Key Value (Preserving Keys)

Learn how to sort a PHP associative array by the values of a specific key while maintaining the original key-value associations using `uasort` and a custom comparison function.

<?php
$users = [
    'john_doe' => ['name' => 'John Doe', 'age' => 30, 'city' => 'New York'],
    'jane_smith' => ['name' => 'Jane Smith', 'age' => 25, 'city' => 'London'],
    'peter_jones' => ['name' => 'Peter Jones', 'age' => 35, 'city' => 'Paris'],
    'alice_wonder' => ['name' => 'Alice Wonder', 'age' => 25, 'city' => 'Berlin'],
];

uasort($users, function($a, $b) {
    // Sort by age, then by name for ties
    if ($a['age'] == $b['age']) {
        return strcmp($a['name'], $b['name']);
    }
    return ($a['age'] < $b['age']) ? -1 : 1;
});

print_r($users);
?>
How it works: This snippet shows how to sort an associative array based on the values of a specific inner key (e.g., 'age' and then 'name' for ties) using `uasort`. The custom comparison function dictates the sorting logic, returning -1, 0, or 1 based on whether the first element is less than, equal to, or greater than the second. `uasort` ensures that the original string keys are preserved, which is crucial for maintaining data integrity.

Need help integrating this into your project?

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

Hire DigitalCodeLabs