How To Sort Arrays in PHP

PHP Array Functions

In PHP, you can sort arrays using various sorting functions and algorithms. Arrays can be sorted by keys or values in ascending or descending order. Accordingly, there are four important functions for sorting arrays - sort(), rsort(), ksort(), krsort().

All these functions always return true.

Example Input Array

$fruits = array('apple' => 4, 'banana' => 2, 'orange' => 1, 'mango' => 3);

1. sort()

This function sorts array by values in ascending order. If two values are equal, they retain their original order in the array.

This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys. The keys of the array will be re-indexed numerically.

Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )

2. rsort()

This function sorts array by values in descending order. The keys of the array will be re-indexed numerically.

Array ( [0] => 4 [1] => 3 [2] => 2 [3] => 1 )

3. ksort()

This function sorts array by keys in ascending order.

Array ( [apple] => 4 [banana] => 2 [mango] => 3 [orange] => 1 )

4. krsort()

This function sorts array by keys in descending order.

Array ( [orange] => 1 [mango] => 3 [banana] => 2 [apple] => 4 )

5. asort()

This function sorts an array in ascending order based on its values while maintaining the association between keys and values.

Array ( [orange] => 1 [banana] => 2 [mango] => 3 [apple] => 4 )

6. arsort()

This function sorts an array in descending order based on its values while maintaining the association between keys and values.

Array ( [apple] => 4 [mango] => 3 [banana] => 2 [orange] => 1 )