Sunday, May 29, 2011

[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.

<?php
$fruits = array(“lemon”, ”orange”, ”banana”, ”apple”);
sort($fruits);
foreach ($fruits as $key => $val) {
echo ”fruits[" . $key . "] = ” . $val . ”\n”;
}
?>
o/p:
fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
asort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>
o/p:
c = apple
b = banana
d = lemon
a = orange

3 comments:

  1. Great information i really get what i was looking for expecting some more information on wed design and development tips..
    Creative web development company | Free lancer websites

    ReplyDelete
  2. Great article and the expression way of describing your services is cool, i like that and wish you all the best , God bless you, thank for sharing this great information with us
    Website Design Company India | Web Design Company India

    ReplyDelete
  3. Useful Information, your blog is sharing unique information....
    Thanks for sharing!!!

    white label website builder

    ReplyDelete