Sort array values alphabetically in PHP

This tutorial is related to PHP array and may be helpful for many of you. Here I am going to show you how you can easily sort a PHP array values alphabetically with the required code examples.

PHP has two inbuilt functions that are going to help us in this tutorial. One is sort() and the other is rsort() function. Using one of these functions, we can sort our PHP array values in alphabetical order.

We will use the sort() function for sorting the array in ascending order. On the other hand, the rsort() function will be used to sort in descending order.

Sorting array values in ascending order

Using the PHP sort() function we can easily sort the array with ascending order. Below is the given PHP code that will do this task:

$arr= array("Tree", "Water", "Butterfly", "Apple", "Mountain", "Desert", "Camel");

If we run the above code, it will show the array given below:

Array ( [0] => Apple [1] => Butterfly [2] => Camel [3] => Desert [4] => Mountain [5] => Tree [6] => Water )

If you notice, you will see that the array is perfectly ordered alphabetically as well as in ascending order.

Sorting array values in descending order

Now we will see an example of sorting array in descending order using the PHP rsort() function. Without wasting any time let’s see the code below to perform our task:

$arr= array("Tree", "Water", "Butterfly", "Apple", "Mountain", "Desert", "Camel");

After we run the above code, we will able to see the array that contains the values in descending order. Below is how the array will look like:

Array ( [0] => Water [1] => Tree [2] => Mountain [3] => Desert [4] => Camel [5] => Butterfly [6] => Apple )

Also, read: Get the maximum value from an array in PHP

So we are successfully able to sort our array values alphabetically with PHP using the sort() and the rsort() function. I hope,  you got a clear idea of this article.

One response to “Sort array values alphabetically in PHP”

  1. ABCD says:

    I really found this content good!.
    I have learned a lot from this platform. Keep posting the good stuff . This has really helped me in my studies.

Leave a Reply

Your email address will not be published. Required fields are marked *