Uly.me

cloud engineer

  • Home
  • About
  • Archives
Home/PHP/Sorting Arrays

November 27, 2012

Sorting Arrays

I was working on a client project last night. I had to sort a multidimensional array. I came across a neat PHP function called asort. In the end, I had to use arsort instead of asort to get a reverse sort order. This short article will show you how to sort arrays in normal and reverse order. Here’s our array.

$animals = array("a" => "Giraffe", "b" => "Elephant", "c" => "Lion");

$animals = array("a" => "Giraffe", "b" => "Elephant", "c" => "Lion");

We will sort the array using the asort function. We print the array to view the results.

asort($animals);
print_r($animals);

asort($animals); print_r($animals);

The asort output is:

Array ( [b] => Elephant [a] => Giraffe [c] => Lion )

Array ( [b] => Elephant [a] => Giraffe [c] => Lion )

The arsort (reverse order) output is:

Array ( [c] => Lion [a] => Giraffe [b] => Elephant )

Array ( [c] => Lion [a] => Giraffe [b] => Elephant )

Filed Under: PHP Tagged With: arrays, arsort, asort

About Me

I'm Ulysses, a Cloud Engineer at Cardinal Health based in Columbus, Ohio. I’m a certified AWS Solutions Architect. This website is my way of documenting the things I have learned in the Cloud. When off the grid, I enjoy riding my electric skateboard. I have surfed, snowboarded and played the saxophone in the past. I hope you will find this site helpful. It's powered by WordPress and hosted in AWS LightSail.

  • Cloud
  • Linux
  • Git

Copyright © 2012–2021