Sorting with sort( ) and rsort( )
The simplest array-sorting functions are sort( ) and rsort( ), which rearrange the elements of the subject array in ascending and descending order, respectively:
sort(array subject [, integer sort_flag]) rsort(array subject [, integer sort_flag])
Both functions sort the subject array based on the values of each element. The following example shows the sort( ) function on an array of integers:
$numbers = array(24, 19, 3, 16, 56, 8, 171); sort($numbers); foreach($numbers as $n) echo $n . " ";
The output of the example prints the elements sorted by value:
3 8 16 19 24 56 171
Another way to examine the contents of the sorted array is to use the print_r( ) function described in Section 2.1.7. The output of the statement print_r($numbers) shows the sorted values with the associated index:
Array ( [0] => 3
[1] => 8
[2] => 16
[3] => 19
[4] => 24
[5] => 56
[6] => 171 )
The following example shows the rsort( ) function on the same array:
$numbers = array(24, 19, 3, 16, 56, 8, 171); rsort($numbers); print_r($numbers);
The output of the example shows the elements sorted in reverse order by value:
Array ( [0] => 171
[1] => 56
[2] => 24
[3] => 19
[4] => 16
[5] => 8
[6] => 3 )
By default, PHP sorts strings in alphabetical order and numeric values in numeric order. An optional parameter, sort_flag, can be passed to force the string or numeric sorting behavior. In the following example, the PHP constant SORT_STRING sorts the numbers as if they were strings:
$numbers = array(24, 19, 3, 16, 56, 8, 171); sort($numbers, SORT_STRING); print_r($numbers);
The output of the example shows the result:
Array ( [0] => 16
[1] => 171
[2] => 19
[3] => 24
[4] => 3
[5] => 56
[6] => 8 )
Many of the array sorting functions accept a sort_flag parameter. Other sort flags are SORT_REGULAR to compare items in the array normally and SORT_NUMERIC that forces items to be compared numerically.
sort( ) and rsort( ) can be used on associative arrays, but the keys are lost. The resulting array contains only the values in the sorted order. Consider the following example:
$map =
array("o"=>"kk", "e"=>"zz", "z"=>"hh", "a"=>"rr");
sort($map);
print_r($map);
The print_r( ) output shows the modified array without the key values:
Array ( [0] => hh [1] => kk [2] => rr [3] => zz )