The elements of an array can be sorted alphabetically or numerically in ascending or descending order.
PHP Functions For Sorting Arrays
In the previous chapter you’ve learnt the essentials of PHP arrays i.e. what arrays are, how to create them, how to view their structure, how to access their elements etc. You can do even more things with arrays like sorting the elements in any order you like.
PHP comes with a number of built-in functions designed specifically for sorting array elements in different ways like alphabetically or numerically in ascending or descending order. Here we’ll explore some of these functions most commonly used for sorting arrays.
sort()
andrsort()
— For sorting indexed arraysasort()
andarsort()
— For sorting associative arrays by valueksort()
andkrsort()
— For sorting associative arrays by key
Sorting Indexed Arrays in Ascending Order : sort() function
The sort()
function is used for sorting the elements of the indexed array in ascending order (alphabetically for letters and numerically for numbers).
<?php $dcs_arr = array("3","4","1","55","5","6","45","44","32","22"); echo "<h1>Origonal array is: </h1>"; echo "<pre>"; print_r($dcs_arr); echo "</pre>"; sort($dcs_arr); echo "<h1>sorted array is: </h1>"; echo "<pre>"; print_r($dcs_arr); echo "</pre>"; ?>
The output will be as given bellow:
Sorting Indexed Arrays in Descending Order : rsort() function
The rsort()
function is used for sorting the elements of the indexed array in descending order (alphabetically for letters and numerically for numbers).
Example:
<?php $dcs_arr = array("3","4","1","55","5","6","45","44","32","22"); echo "<h1>Origonal array is: </h1>"; echo "<pre>"; print_r($dcs_arr); echo "</pre>"; rsort($dcs_arr); echo "<h1>sorted array is: </h1>"; echo "<pre>"; print_r($dcs_arr); echo "</pre>"; ?>
The output will be:
Sorting Associative Arrays in Ascending Order By Value
The asort()
function sorts the elements of an associative array in ascending order according to the value. It works just like sort()
, but it preserves the association between keys and its values while sorting.
Example:
<?php $dcs_arr_asso = array ( 'num1' => 10, 'num2' => 4, 'num3' => 130, 'num4' => 12, 'num5' => 112, 'num6' => 15, 'num7' => 6, 'num8' => 170, 'num9' => 106, 'num10' => 104, ); echo "<h1>Origonal array is: </h1>"; echo "<pre>"; print_r($dcs_arr_asso); echo "</pre>"; asort($dcs_arr_asso); echo "<h1>sorted array is: </h1>"; echo "<pre>"; print_r($dcs_arr_asso); echo "</pre>"; ?>
If you have any question relating the topic, you can ask it at our Forum Section.