PHP sort Arrays

Tags: , ,

In the previous tutorial, we have used examples to learn PHP arrays.  In this post, we talk about how to sort php Arrays based on different needs.

Here are the functions we can use to sort a PHP array:

  • rsort() Sorts an indexed array in descending order   
  • sort() Sorts an indexed array in ascending order
  • arsort() Sorts an associative array in descending order, according to the value
  • asort() Sorts an associative array in ascending order, according to the value
  • krsort() Sorts an associative array in descending order, according to the key
  • ksort() Sorts an associative array in ascending order, according to the key  
  • natcasesort() Sorts an array using a case insensitive “natural order” algorithm
  • natsort() Sorts an array using a “natural order” algorithm         
  • uasort() Sorts an array by values using a user-defined comparison function
  • uksort() Sorts an array by keys using a user-defined comparison function
  • usort() Sorts an array using a user-defined comparison function

Here are some examples to show how to call these sort functions to sort a php array.

sort arrays in ascending order

The following code sorts the elements of the $letters array in ascending alphabetical order:

Sort Array in Descending Order

We can use rsort() to sort arrays in descending order. 

The following code sorts the elements of the $letters array in descending alphabetical order:

Sort associated Array asc based on Value

asort() can be used to sort an associated array based on the values in ascending order.

The following code sorts an associative array in ascending order based on the value: 

Sort Array in asc based on Key

 ksort() can be used to sort a php array in ascending order based on key. The following codes sorts the array based on the name in asc order.

PHP uasort() Function

We can sort a php array by keys based on a user defined function.

Reference:

http://www.w3schools.com/php/php_ref_array.asp

http://php.net/manual/en/language.types.array.php