Looking to Build/Redesign a Website or Blog ?

To speak to Rakshit, call +91 968 704 2303

[PHP] What is the difference between sort & asort in php ?

Many times developers are not aware with the core functions of PHP. PHP have sort and asort built in array functions. You may or may not be aware with these functions. But when you will face a PHP interview than you may be asked for this question. What is the difference between sort & asort in php ? From the name itself, you can say it will sort an array elements but you may not be aware with the exact difference.

sort() function will sort an array by values and array keys will be automatically reset.
asort() function will sort an array by values and array keys will be the same as per original array.

For e.g.

<?php
	$arr = array("0"=>"Rakshit","1"=>"Patel","2"=>"PHP","3"=>"Freelancer");
    sort($arr);
    print_r($arr);
    // Output
    [0] => "Freelancer"
    [1] => "Patel"
    [2] => "PHP"
    [3] => "Rakshit"
 
    $arr = array("0"=>"Rakshit","1"=>"Patel","2"=>"PHP","3"=>"Freelancer");
    asort($arr);
    print_r($arr);
    // Output
    [3] => "Freelancer"
    [1] => "Patel"
    [2] => "PHP"
    [0] => "Rakshit"
?>
Share:

3 Comments

Leave a Reply

Your email address will not be published.