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.
// 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]
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?