In PHP, how do I sort arrays with examples?

Sorting arrays in PHP can be accomplished using various built-in functions depending on the array's structure and the desired sorting order. Below are some common methods to sort arrays in PHP along with examples.

Keywords: PHP, array sorting, sort, asort, ksort, usort, rsort, array_multisort
Description: Learn how to efficiently sort arrays in PHP using built-in functions, including examples for associative and indexed arrays.
        
// Example of sorting a simple indexed array
$arr = [5, 2, 9, 1, 5, 6];
sort($arr);
print_r($arr); // Output: [1, 2, 5, 5, 6, 9]

// Example of sorting an associative array by value
$assocArr = ['a' => 3, 'b' => 1, 'c' => 2];
asort($assocArr);
print_r($assocArr); // Output: Array ( [b] => 1 [c] => 2 [a] => 3 )

// Example of sorting an associative array by key
ksort($assocArr);
print_r($assocArr); // Output: Array ( [a] => 3 [b] => 1 [c] => 2 )

// Example of sorting an array using a custom comparison function
$customArr = [5, 2, 9, 1, 5, 6];
usort($customArr, function($a, $b) {
    return $b <=> $a; // Sort in descending order
});
print_r($customArr); // Output: [9, 6, 5, 5, 2, 1]
        
    

Keywords: PHP array sorting sort asort ksort usort rsort array_multisort