We know that array is the collection of data in list form, but what if we need to sort the data or sort it in reverse order or if we want to sort the array based on keys, not values? No problem in PHP guys, it’s easy and simple. Let’s have a look.

Sorting the array data.

<?php
     $flower[0]=”Rose”;
     $flower[1]=”Lily”;
     $flower[2]=”Tulip”;
     print_r($flower);
     sort($flower);
     echo “<br>After Sorting<br>”;
     print_r($flower);
?>

 

Here is the result:

Array
(
     [0] => Rose
     [1] => Lily
     [2] => Tulip
)

After Sorting

Array
(
     [0] => Lily
     [1] => Rose
     [2] => Tulip
)

Cool huh! How about reverse sort.

<?php

     $flower[0]=”Rose”;
     $flower[1]=”Lily”;
     $flower[2]=”Tulip”;
     print_r($flower);
     rsort($flower);
     echo “<br>After Reverse Sorting<br>”;
     print_r($flower);

?>

 

Here is the result:

Array
(
     [0] => Rose
     [1] => Lily
     [2] => Tulip
)

After Reverse Sorting

Array
(
     [0] => Tulip
     [1] => Rose
     [2] => Lily
)

 

This thing will not work if you’re using text string keys in the arrays instead of numeric index values. The text string keys will just be replaced by numbers. To do sort here in this kind of situation, use asort instead. Have look below.

<?php

     $flower[“lovely”]=”Rose”;
     $flower[“great”]=”Lily”;
     $flower[“rockstar”]=”Tulip”;
     print_r($flower);
     asort($flower);
     echo “<br>After Sorting by asort<br>”;
     print_r($flower);

?>

 

Here is the result:

Array
(
     [lovely] => Rose
     [great] => Lily
     [rockstar] => Tulip
)

After Sorting by asort

Array
(
     [great] => Lily
     [lovely] => Rose
     [rockstar] => Tulip
)

 

And what if we want reverse sorting here, to do that we will use arsort().

We can do sorting based on keys not on data. This can be done by using ksort() and for reverse key sort, use krsort().

Hope you guys like it.

If you have any issue, let us know in the comment box.
Happy Coding.