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

Answer Posted / hardik

) 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 ?    4 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

I need to know about the courses which are useful in corporate companies.. especially php/mySQL, Java/j2ee, .NET.. also tell if any other courses are valuable

1514


What is regular expression in php?

531


How do you end php?

504


How to pass variables by references?

550


Is php used in 2019?

524






What is rest api in php?

508


How do I find out the number of parameters passed into function9?

538


How to reset/destroy a cookie?

569


What is mysql in php?

513


A process is identified by a unique___

588


What is delimiter php?

523


What is php artisan serve?

515


How is traits used in php?

525


What is the difference between query and question?

512


What is the current php version?

546