If you want to sort an array in ascending or descending order in PHP you can use sort()
(for ascending) and rsort()
(for descending) functions and easily sort the elements of the array. If your array is $array
, use sort($array)
or rsort($array)
and rearrange the elements to see the new order.
In this topic, we will see how we can use sort()
and rsort()
functions on the array and display the elements in ascending or descending order in a PHP program. Look below code how it is used:
Here, we have the array $languages
and we are using sort()
and rsort()
functions on the array. We can use var_dump()
to display the new order:
sort()
array(5) { [0]=> string(5) "Basic" [1]=> string(3) "C++" [2]=> string(4) "Java" [3]=> string(3) "PHP" [4]=> string(6) "Python" }
rsort()
array(5) { [0]=> string(6) "Python" [1]=> string(3) "PHP" [2]=> string(4) "Java" [3]=> string(3) "C++" [4]=> string(5) "Basic" }
You can also read below topics related to this:
- How to populate an array from MySQL database in PHP
- How to check if an element exists in an array in PHP
- How to sort array values in PHP in ascending or descending order
- How to create two dimensional array from database in PHP and MySQL
Now, let us write a program which will display original array and the new array (sorted) in ascending and descending order. We will write html and PHP code to display output in the browser. Let's take a look at below code:
We want to reorder the array $languages
in ascending order and then descending order. We are displaying the original array and then we used sort($languages)
to sort it in ascending order. Similarly, by using rsort($languages)
, we are displaying them in descending order.
Let us save this program as index.php
under xampp/htdoc/array folder.
If we run this in the browser using localhost/array, below output is displayed:
So, this was an example of how you can sort and display an array in PHP.