Sorting an array

Hi all,

I have a an array with car names and a random number against each car name. How can I order this by having highest random number at the top and the lowest random number at the bottom?

So far my code is:

$cars = array
  (
  array("bmw",mt_rand(30, 100)),
  array("ford",mt_rand(30, 100)),
  array("mg",mt_rand(30, 100)),
  array("mercedes",mt_rand(30, 100))
  );

for ($row = 0; $row < 4; $row++) {
  echo "<p><b>Row number $row</b></p>";
  echo "<ul>";
  for ($col = 0; $col < 3; $col++) {
    echo "<li>".$cars[$row][$col]."</li>";
  }
  echo "</ul>";
}

Im almost there with it but need a bit of help. :slight_smile:

You could try something with

https://www.php.net/manual/en/function.array-multisort.php

but i would prefer using

https://www.php.net/manual/en/function.usort.php

with a custom function. The spaceship-operator can help, too.

https://wiki.php.net/rfc/combined-comparison-operator

1 Like