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
What is a null coalescing operator in php7?
Explain about getters and setters in php?
What is the use of header() function in PHP? What the Limitation of HEADER()?
What type of headers have to be added in the mail function to attach a file?
What are getters and setters php?
Tell me how can we determine whether a php variable is an instantiated object of a certain class?
where do we use htaccess?
How to check curl is enabled or not in PHP
What is mysql_fetch_row?
How is it possible to return a value from a function?
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?
What is the use of pear in php?
What is the use of final class in php?
What is the difference between $name and $$name?
Explain the installation of PHP on UNIX systems?