What’s the difference between sort(), assort() and ksort?
Under what circumstances would you use each of these?

Answer Posted / deep

1) sort()
This function sorts an array. Elements will be arranged
from lowest to highest when this function has completed.

<?php

$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
echo "fruits[" . $key . "] = " . $val . "\n";
}

?>
----------------------------OUTPUT---------------------
fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange
-------------------------------------------------------

2) asort()
This function sorts an array such that array indices
maintain their correlation with the array elements they are
associated with. This is used mainly when sorting
associative arrays where the actual element order is
significant.

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

--------------------OUTPUT------------------------
c = apple
b = banana
d = lemon
a = orange
--------------------------------------------------

3) ksort()
Sorts an array by key, maintaining key to data
correlations. This is useful mainly for associative arrays.

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

--------------------OUTPUT----------------------------
a = orange
b = banana
c = apple
d = lemon
------------------------------------------------------

Is This Answer Correct ?    28 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is a null coalescing operator in php7?

729


Explain about getters and setters in php?

535


What is the use of header() function in PHP? What the Limitation of HEADER()?

569


What type of headers have to be added in the mail function to attach a file?

550


What are getters and setters php?

545






Tell me how can we determine whether a php variable is an instantiated object of a certain class?

560


where do we use htaccess?

546


How to check curl is enabled or not in PHP

636


What is mysql_fetch_row?

550


How is it possible to return a value from a function?

542


If we login more than one browser windows at the same time with same user and after that we close one window, then is the session is exist to other windows or not? And if yes then why? If no then why?

490


What is the use of pear in php?

561


What is the use of final class in php?

508


What is the difference between $name and $$name?

528


Explain the installation of PHP on UNIX systems?

551