Write an Article
PHP gives us lot of array functions but when we want to sort an array in easier way. Here is the simple function that is uasort(). The uasort() function sort an array with user defined comparison function and can also easily maintain index association.
Now, How to sort an array in place which its keys maintain their connection with the values they are associated. (user defined comparison function).
Parameters:- function has only two parameters which is mention below.
uasort($array, callback);
<?php
function comparisonFunction($b, $c) {
if ($b == $c) {
return 0;
}
return ($b < $c) ? -1 : 1;
}
// Array to be sorted
$array = array(
'a' => 9,
'b' => 2,
'c' => -3,
'd' => -9,
'e' => 6,
'f' => 5,
'g' => 7,
'h' => -4
);
// Sort and print the resulting array
uasort($array, 'comparisonFunction');
print_r($array);
?>
Array ( [d] => -9 [h] => -4 [c] => -3 [b] => 2 [f] => 5 [e] => 6 [g] => 7 [a] => 9 )