0

I am trying to sort $ar1 by the descending order values of $ar2. Nothing is happening.

$ar1 = array($arperc);
$ar2 = array($arid);
array_multisort($ar1, $ar2);
print_r($ar1);

What am I missing?

4
  • 2
    Could you give us examples for the values of $arperc and $arid? Commented Dec 7, 2011 at 21:53
  • 1
    your arguments are the wrong way around :D Commented Dec 7, 2011 at 21:54
  • 1
    You really need to provide some example data to allow us to solve that.. But it seems that you send in an array with just one value? You probably want to just create a copy with $ar1 = $arperc; if you don't want to sort the original array. Commented Dec 7, 2011 at 21:54
  • Are these single element arrays? Are these multi-dimensional arrays? We don't know. These is no minimal reproducible example. Commented Apr 3, 2023 at 9:44

1 Answer 1

2

If you want to use the elements of $ar2 as sorting keys, you need to change the order of arguments to array_multisort:

array_multisort($ar2, $ar1);

This will sort $ar2 in ascending order, and also change the order of $ar1 elements exactly as the order of $ar2 is changed by the sorting. To change the order to descending:

array_multisort($ar2, SORT_DESC, $ar1);
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, the PHP documentation is really terrible in explaining how to use that function. I've also got that wrong. And it always worked, until it didn't. So if the first array is also being sorted, it must be an unintended side effect. stackoverflow.com/q/75836843/143684

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.