PHP array sorting
The elements in the array can be arranged in descending or ascending order alphabetically or numerically.
Ascending order: Sort from small to large. If it is an English word, then sort it in the order of letters A-Za-z. If it is a number, then Sort by numerical size.
Descending order: The opposite of ascending order
Array sorting function
In this chapter, we will introduce the following PHP array sorting functions one by one:
·sort()- Sort the array in ascending order
·rsort()- Sort the array in descending order
·asort()- Sort the array in ascending order according to the value of the associative array
·ksort()- Sort the array in ascending order according to the keys of the associative array
·arsort()- Sort the array in descending order according to the values of the associative array
·krsort()- Sort the array in descending order according to the key of the associative array
sort() function
##Note: sort is mostly Used to sort numeric index arrays. If an associative array is put into sort for sorting, the keys of the array will be lost
Example
The following example sorts the elements in the array in ascending order:
The following is the result of the program running: As can be seen from the above example, we have used
sort()function sorts the array in ascending order. You may wish to replace thesort()function with rsort() to see what changes there are.
Little Thoughts
Since associative arrays cannot be sorted using sort, what function should be used?
This will use theasort()function we learned below
asort() function
Example
The following example sorts the associative array in ascending order based on the value of the array:
"25","Andy"=>"18","Joe"=>"23","Ben"=>"28"); asort($age); print_r($age); ?>
Through the running results of the above example, we can see that the asort() function actually uses the value of the array to sort, so if we want to sort the keys, we can use
ksort() function
ksort() function
Example
#The following example sorts the associative array in ascending order according to the key of the array:
"25","Andy"=>"18","Joe"=>"23","Ben"=>"28"); ksort($age); print_r($age); ?>
A few examples above We all sort the array in ascending order. You might as well try to sort the array in descending order. The usage is the same. Give it a try
Complete PHP Array Reference Manual
For a complete reference manual for array functions, please visit our PHP Array Reference Manual.
This reference manual contains a brief description and usage examples of each function.