[ Team LiB ] Previous Section Next Section

Sorting Arrays

Sorting is perhaps the greatest magic you can perform on an array. Thanks to the functions PHP offers to achieve just this, you can truly bring order from chaos. This section introduces some functions that allow you to sort both numerically indexed and associative arrays.

Sorting Numerically Indexed Arrays with sort()

sort() accepts an array as its argument and sorts it either alphabetically if any strings are present or numerically if all elements are numbers. The function doesn't return any data, transforming the array you pass it. Note that it differs from Perl's sort() function in this respect. The following fragment of code initializes an array of single character strings, sorts it, and outputs the transformed array:


$an_array = array ("x", "a", "f", "c");
sort( $an_array );

foreach ( $an_array as $var ) {
  print "$var<br />";
}

graphics/watchout_icon.gif

Don't pass an associative array to sort(). You will find that the values are sorted as expected but that your keys have been lost—replaced by numerical indices that follow the sort order.


You can reverse sort a numerically indexed array by using rsort() in exactly the same way as sort().

Sorting an Associative Array by Value with asort()

asort() accepts an associative array and sorts its values just as sort() does. However, it preserves the array's keys:


$first = array("first"=>5,"second"=>2,"third"=>1);
asort( $first );

foreach ( $first as $key => $val ) {
  print "$key = $val<br />";
}

You can see the output from this fragment of code in Figure 7.5.

Figure 7.5. Sorting an associative array by its values with asort().

graphics/07fig05.gif

You can reverse sort an associative array by value with arsort().

Sorting an Associative Array by Key with ksort()

ksort() accepts an associative array and sorts its keys. Once again, the array you pass it is transformed and nothing is returned:


$first = array("x"=>5,"a"=>2,"f"=>1);
ksort( $first );

foreach ( $first as $key => $val ) {
  print "$key = $val<br />";
}

You can see the output from this fragment of code in Figure 7.6.

Figure 7.6. Sorting an associative array by its keys with ksort().

graphics/07fig06.gif

You can reverse sort an associative array by key with krsort().

    [ Team LiB ] Previous Section Next Section