Page 161 - Beginning PHP 5.3
P. 161
Chapter 6: Arrays
This is where asort() and arsort() come in. They work just like sort() and rsort() , but they
preserve the association between each element ’ s key and its value:
$myBook = array( “title” = > “Bleak House”,
“author” = > “Dickens”,
“year” = > 1853 );
// Displays “Array ( [title] = > Bleak House [author] = > Dickens [year] = >
1853 )”
asort( $myBook );
print_r( $myBook );
// Displays “Array ( [year] = > 1853 [author] = > Dickens [title] = > Bleak
House )”
arsort( $myBook );
print_r( $myBook );
Note that although you can use asort() and arsort() on indexed arrays, they ’ re commonly used
with associative arrays.
Sorting Associative Array Keys with ksort() and krsort()
ksort() and krsort() behave in much the same way as asort() and arsort() , in that they sort
arrays in ascending and descending order, respectively, preserving the associations between keys and
values. The only difference is that, whereas asort() and arsort() sort elements by value, ksort()
and krsort() sort the elements by their keys:
$myBook = array( “title” = > “Bleak House”,
“author” = > “Dickens”,
“year” = > 1853 );
// Displays “Array ( [author] = > Dickens [title] = > Bleak House [year] = >
1853 )”
ksort( $myBook );
print_r( $myBook );
// Displays “Array ( [year] = > 1853 [title] = > Bleak House [author] = >
Dickens )”
krsort( $myBook );
print_r( $myBook );
In this example, ksort() has sorted the array by key in ascending order ( “ author ”,
“ title ”, “ year “ ), whereas krsort() has sorted by key in the opposite order.
As with asort() and arsort() , ksort() and krsort() tend to be used mainly with associative
arrays.
123
c06.indd 123
9/21/09 9:00:17 AM
c06.indd 123 9/21/09 9:00:17 AM