How to sort array values in PHP in ascending or descending order

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:


array(5) { [0]=> string(5) "Basic" [1]=> string(3) "C++" [2]=> string(4) "Java" [3]=> string(3) "PHP" [4]=> string(6) "Python" }


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:

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:

Array Sort in php

So, this was an example of how you can sort and display an array in PHP.

sort an array in PHPConclusion

In this simple topic, I have just tried to show how you can sort elements of an array using PHP functions. It all depends on your project requirement how you can apply them to achieve a specific need. I used an indexed array here. If you have an associative array, use asort() or ksort(), because then you have to maintain the key-value association.