Page 160 - Beginning PHP 5.3
P. 160
Part II: Learning the Language
sorted. The function then sorts the array. As with all the sorting functions covered in this chapter, the
function returns true if it managed to sort the array or false if there was a problem.
Here ’ s an example that sorts a list of authors alphabetically in ascending order, and then in
descending order:
$authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
// Displays “Array ( [0] = > Dickens [1] = > Kafka [2] = > Steinbeck [3] = >
Tolkien )”
sort( $authors );
print_r( $authors );
// Displays “Array ( [0] = > Tolkien [1] = > Steinbeck [2] = > Kafka [3] = >
Dickens )”
rsort( $authors );
print_r( $authors );
Sorting Associative Arrays with asort() and arsort()
Take another look at the previous sort() and rsort() code examples. Notice how the values in the
sorted arrays have different keys from the values in the original array. For example, “ Steinbeck ” has an
index of 0 in the original array, 2 in the second array, and 1 in the third array. The sort() and rsort()
functions are said to have reindexed the original array.
For indexed arrays, this is usually what you want to happen: you need the elements to appear in the
correct order, and at the same time you expect the indices in an indexed array to start at zero. However,
for associative arrays, this can cause a problem. Consider the following scenario:
$myBook = array( “title” = > “Bleak House”,
“author” = > “Dickens”,
“year” = > 1853 );
sort( $myBook );
// Displays “Array ( [0] = > Bleak House [1] = > Dickens [2] = > 1853 )”
print_r( $myBook );
Notice how sort() has reindexed the associative array, replacing the original string keys with numeric
keys and effectively turning the array into an indexed array. This renders the sorted array practically
useless, because there ’ s no longer an easy way to find out which element contains, say, the book title.
122
9/21/09 9:00:17 AM
c06.indd 122 9/21/09 9:00:17 AM
c06.indd 122