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:

4 Comments

  • […] these functions. But when you will face a PHP interview than you may be asked for this question…. [full post] Rakshit Patel Programming Facts helpful tips and tricksphp programming 0 […]

  • paras

    Hello

    Hope doing well
    if you are PHP freelancer and looking for australian project
    kindly contact on 8128320044

    Thanks
    Paras Parmar

  • Prabhu

    sort() function will sort the array in ascending values only not its key.
    asort() function sorts the array in ascending value and maintains the
    key/value relationship.

  • Arnottsimon

    Basically sort() and asort() functions are used to sort the array in php.
    Specifies how to sort the array values. some of the sort function

    * SORT_REGULAR – Default. values (dont change types)
    * SORT_NUMERIC – values numerically
    * SORT_STRING – values as strings
    * SORT_LOCALE_STRING – Treat values as strings

Leave a Reply

Your email address will not be published.