Home > CakePHP, Php programming > [PHP] What is the difference between sort & asort in php ?

[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
Advertisements
Categories: CakePHP, Php programming Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: