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
How check variable is set or not in php?
Will php die?
What is cookies? How to create cookies in php?
Is ruby on rails php?
Explain the advantages of using PHP?
What is super keyword in c++?
where do we use htaccess?
What is alias in php?
Under what circumstance is it impossible to assign a default value to a parameter while declaring a function?
What is the use of "enctype" attribute in a html form?
Explain the difference between urlencode and urldecode?
Which is true about the singleton design pattern?
Is php a low level language?
Explain what are some new features introduced in php7?
What is the difference between pop3 IMAP and MAPI?