PHP Sorting Arrays

You learned the fundamentals of PHP arrays in the previous tutorial, including what arrays are, how to construct them, how to view their structure, and how to access their components. Arrays allow you to do even more things, such as sort the elements in any order you want.

PHP has a variety of built-in functions for sorting array elements in various ways, including alphabetically, numerically, and in ascending or descending order. We'll look at some of the most popular functions for sorting arrays in this section.


Ascending Sorting of Indexed Arrays

The sort() function is used to sort the elements of an indexed sequence in ascending order (alphabetically for letters and numerically for numbers).


<?php
  // Define array
  $colors = array("Red", "Green", "Blue", "Yellow");
  echo 'Array before sorting:<br>';
  print_r($colors);
  // Sorting and printing array
  echo "Array after sorting<br>";
  sort($colors);
  print_r($colors);
?>


Output

Array before sorting:
Array ( [0] => Red [1] => Green [2] => Blue [3] => Yellow )
Array after sorting
Array ( [0] => Blue [1] => Green [2] => Red [3] => Yellow )


Descending Order Sorting of Indexed Arrays

The indexed array's elements are sorted in ascending order using the rsort() function (alphabetically for letters and numerically for numbers).


<?php
  // Define array
  $colors = array("Red", "Green", "Blue", "Yellow");

  // Sorting and
  // printing array
  rsort($colors);
  print_r($colors);
?>