PHP asort() example

This tutorial shows an example how to sort an array using asort() function available in PHP. The asort() function sorts an array by maintaining the index association.

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.

Create a php webpage called asort.php with the below source code.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>PHP asort() example</title>
    </head>
    <body>
        <?php
        $array1 = array("img22.png", "img20.png", "img4.png", "img2.png");
        echo 'Before sorting => ';
        print_r($array1);
        
        echo "<br/>";
        
        asort($array1);
        
        echo 'After sorting => ';
        print_r($array1);
        ?>
    </body>
</html>

If you run the above file then you will get output as shown below

php asort

Thanks for reading.

Leave a Reply

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