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

What is meant by urlencode and urldecode?

610


How long is csrf token?

542


How to take a substring from a given string in php?

520


What are html entities?

507


How can you pass a variable by reference?

559






Tell us what is the difference between session_unregister() and session_unset()?

557


Explain how can we execute a php script using command line?

505


What is orm in php framework?

502


What is php artisan tinker?

509


How many records can be stored in mysql table?

552


What is the meaning of symbol '$' in jquery?

538


Do you know what is php?

555


How are sessions maintained?

541


Write syntax to open a file in php?

520


How can you declare the array in php?

523