Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access array key using uasort in PHP

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?

like image 250
mmvsbg Avatar asked Jul 02 '15 11:07

mmvsbg


People also ask

How uasort works?

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);

What is Uasort PHP?

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.

What does Uasort () function returns on failure?

The uasort() function returns true on success or false on failure. The $callback function returns an integer.

How do you Unsort an array in PHP?

PHP usort() Function $a=array(4,2,8,6); usort($a,"my_sort");


1 Answers

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.

like image 96
deceze Avatar answered Oct 07 '22 11:10

deceze