If have a rather basic uasort
function in PHP that looks like this:
uasort($arr, function($a, $b) {
if ($a > $b)
return -1;
if ($a < $b)
return 1;
...
}
The array I'm trying to sort looks like the following:
{[1642] => 1, [9314] => 4, [1634] => 3 ...}
It contains integers that are my main comparison criteria. However, if the integers are equal, then I would like to access their key values, inside the uasort
function and do some magic with it to figure out the sorting from there.
I have no clue how to do that as it seems that the $a
and $b
variables that get passed into the function are just the integers without the corresponding keys but there should be a way to access the key as well since I'm using a function to actually preserve the keys. Any ideas?
The uasort() function is a builtin function in PHP and is used to sort an array such that array indices maintain their correlation with the array elements they are associated with, using a user-defined comparison function. Syntax: boolean uasort(array_name, user_defined_function);
The uasort() function sorts an array by values using a user-defined comparison function. Tip: Use the uksort() function to sort an array by keys using a user-defined comparison function.
The uasort() function returns true on success or false on failure. The $callback function returns an integer.
PHP usort() Function $a=array(4,2,8,6); usort($a,"my_sort");
uksort($arr, function ($a, $b) use ($arr) {
return $arr[$a] - $arr[$b] ?: $a - $b;
});
You can get the values by the keys, so use uksort
which gives you the keys. Replace $a - $b
with your appropriate magic, here it's just sorting by the key's value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With