Sorting Arrays-PHP


PHP supports a variety of ways to sort an array when 
I say sort, I am referring to an alphabetical sort if it is a string,
 and a numerical sort if it is a number. When sorting an array, 
you must keep in mind that an array consists of several pairs 
of keys and values. Thus, an array can be sorted based upon
 the values or the keys. Also, you can sort the values and keep 
the corresponding keys matched up or sort the values and 
have them receive new keys.
To sort the values, without regard to the keys, 
you use sort(). 
 To sort these values again without regard to the keys,
 in reverse order, you use rsort(). 
The syntax for every sorting function is like this:

function($Array);
So, sort() and rsort() are simply:
sort($Array);
rsort($Array);
 
To sort the values, while maintaining the correlation
 between the value and its key, you use asort(). 
To sort them in reverse, while maintaining the key
 correlation, you use arsort().
To sort by the keys, while still maintaining the correlation
 between the key and its value, you use ksort(). 
Conversely, krsort() will sort the keys in reverse.
Last, shuffle() randomly reorganizes the order of an array.

As an example of sorting arrays, you'll create a list of students
 and the grades they received on a test, then sort this list first
 by grade then by name.

Create the array:
 
$Grades = array(
"Richard"=>"95",
"Sherwood"=>"82",
"Toni"=>"98",
"Franz"=>"87",
"Melissa"=>"75",
"Roddy"=>"85"
);


 Print a caption and then print each element of 
the array using a loop.

print ("Originally, the array looks
 like this:<BR>");
for ($n = 0; $n < count($Grades);
 $n++) {
   $Line = each ($Grades);
   print ("$Line[key]'s grade is
 $Line[value].<BR>\n");
}


Sort the array in reverse order by values to determine 
who had the highest grade.

arsort($Grades);
 
Because you are determining who has the highest 
grade, you need to use arsort() instead of asort(). 
The latter, which sorts the array by numeric order, would 
order them 75, 82, 85, etc. and not the desired 98, 95, 87, etc.