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

6 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. Really an interesting and amazing post. Thanks for sharing this wonderful informative article here. I appreciate your hard work.SEO Companies Bangalore | Digital Marketing Company Bangalore

    ReplyDelete
  3. 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
  4. This is very good information to now days the webdesign is more powerful one in the business.. and also i must learn the full concept in the webdesign thanks to sharing the wonderful information....Web Design Company Bangalore | Website Development Company Bangalore

    ReplyDelete
  5. I was reading your web designing post. It was amazing and nice information Great lists that really presents at lot of interesting examples.
    Web development Company in India Company | Web development Company Bangalore
    Web Development Company in Bangalore | Responsive Web development

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

    white label website builder

    ReplyDelete