PHP Sorting Arrays

Array sorting provides a way to organize data sets in either alphabetical order or in numbers, in an ascending or descending manner.

PHP provides inbuilt functions to sort an array. Here are the list.

  1. sort() – sorts arrays in ascending order
  2. rsort() – sorts arrays in descending order
  3. asort() – sorts associative arrays in ascending order, according to the value
  4. ksort() – sorts associative arrays in ascending order, according to the key
  5. arsort() – sorts associative arrays in descending order, according to the value
  6. krsort() – sorts associative arrays in descending order, according to the key

Following is example code to use array sorting function:

<?php
// Define array
$colors = array("Red", "Green", "Blue", "Yellow");
 
// Sorting and printing array
sort($colors);
print_r($colors);
?>

Output is as following:

Array ( [0] => Blue [1] => Green [2] => Red [3] => Yellow ) 

Hope it helps.

2 thoughts on “PHP Sorting Arrays

Leave a comment