What are potential pitfalls when sorting arrays in PHP, especially when dealing with complex array structures?
When sorting arrays in PHP, one potential pitfall is losing the original keys of the array elements. To maintain the original keys while sorting, you can use the `uasort()` function in PHP, which sorts an array by values using a user-defined comparison function while maintaining key association.
// Sample array with original keys
$array = array(
'b' => 4,
'a' => 2,
'c' => 6
);
// Custom comparison function to maintain original keys
function customSort($a, $b) {
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
// Sort the array by values while maintaining original keys
uasort($array, 'customSort');
// Output the sorted array with original keys preserved
print_r($array);