What are some common pitfalls to avoid when sorting arrays in PHP to ensure accurate and consistent results?
One common pitfall to avoid when sorting arrays in PHP is not specifying the sorting method. By default, PHP's `sort()` function sorts arrays in ascending order, but if you need to sort in descending order, you must explicitly specify it. Another pitfall is not using the correct comparison function for custom sorting criteria, which can lead to inaccurate results. To ensure accurate and consistent sorting results, always specify the sorting method and use the appropriate comparison function.
// Example of sorting an array in descending order
$array = [3, 1, 5, 2, 4];
rsort($array);
print_r($array);
// Example of sorting an array with a custom comparison function
$array = ["apple", "banana", "cherry"];
usort($array, function($a, $b) {
return strlen($b) - strlen($a);
});
print_r($array);