Consider
the following example:
$states = array("OH" => "Ohio", "CA" => "California", "MD" => "Maryland");
sort($states);
print_r($states);
148 CHAPTER 5 ?– ARRAYS
Here??™s the output:
Array ( [0] => California [1] => Maryland [2] => Ohio )
To maintain these associations, use asort(), introduced next.
Sorting an Array While Maintaining Key/Value Pairs
The asort() function is identical to sort(), sorting an array in ascending order,
except that the key/value correspondence is maintained. Its prototype follows:
void asort(array array [,integer sort_flags])
Consider an array that contains the states in the order in which they joined the
Union:
$state[0] = "Delaware";
$state[1] = "Pennsylvania";
$state[2] = "New Jersey";
Sorting this array using sort() causes the associative correlation to be lost, which
is probably a bad idea. Sorting using sort() produces the following ordering:
Array ( [0] => Delaware [1] => New Jersey [2] => Pennsylvania )
However, sorting with asort() produces the following:
Array ( [0] => Delaware [2] => New Jersey [1] => Pennsylvania )
If you use the optional sort_flags parameter, the exact sorting behavior is determined
by its value, as described in the sort() section.
CHAPTER 5 ?– ARRAYS 149
Sorting an Array in Reverse Order
The rsort() function is identical to sort(), except that it sorts array items in reverse
(descending) order.
Pages:
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229