← Back to all snippets
PHP

Sorting PHP Associative Arrays by Key or Value

Learn how to efficiently sort PHP associative arrays. This snippet demonstrates sorting by values (ascending/descending) using asort/arsort and by keys using ksort/krsort, preserving key-value associations.

<?php
$data = [
    'apple' => 5,
    'banana' => 2,
    'cherry' => 8,
    'date' => 1
];

// Sort by value (ascending)
$sortedByValueAsc = $data;
asort($sortedByValueAsc);
// Result: ['date' => 1, 'banana' => 2, 'apple' => 5, 'cherry' => 8]

// Sort by value (descending)
$sortedByValueDesc = $data;
arsort($sortedByValueDesc);
// Result: ['cherry' => 8, 'apple' => 5, 'banana' => 2, 'date' => 1]

// Sort by key (ascending)
$sortedByKeyAsc = $data;
ksort($sortedByKeyAsc);
// Result: ['apple' => 5, 'banana' => 2, 'cherry' => 8, 'date' => 1]

// Sort by key (descending)
$sortedByKeyDesc = $data;
krsort($sortedByKeyDesc);
// Result: ['date' => 1, 'cherry' => 8, 'banana' => 2, 'apple' => 5]

// Custom sorting with uasort (by value length example)
$fruits = [
    'mango' => 'sweet',
    'lemon' => 'sour',
    'grape' => 'juicy'
];
uasort($fruits, function($a, $b) {
    return strlen($a) <=> strlen($b);
});
// Result: ['lemon' => 'sour', 'mango' => 'sweet', 'grape' => 'juicy']
?>
How it works: This snippet demonstrates various ways to sort associative arrays in PHP while maintaining the key-value association. `asort()` sorts by value in ascending order, `arsort()` in descending. `ksort()` sorts by key in ascending order, `krsort()` in descending. For custom sorting logic, `uasort()` allows defining a comparison function, useful for complex criteria like string length as shown.

Need help integrating this into your project?

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

Hire DigitalCodeLabs