How does the use of sort() impact the integrity of key-value pairs in PHP arrays, especially when dealing with complex array manipulation?
When using the `sort()` function in PHP on an associative array, the key-value pairs can become disassociated, as `sort()` reorders the elements based on their values while maintaining numerical keys. To maintain the integrity of key-value pairs during complex array manipulation, you can use `uasort()` instead, which sorts the array by values while preserving key-value associations.
// Sample associative array
$myArray = array("key1" => 5, "key2" => 3, "key3" => 7);
// Custom sorting function to sort by values while maintaining key-value pairs
function customSort($a, $b) {
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
// Using uasort() to sort the array by values while preserving key-value associations
uasort($myArray, 'customSort');
// Output the sorted array with key-value pairs intact
print_r($myArray);