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

Why print_r is used in php?

535


What does it mean when it says the csrf token is invalid?

498


What are the special characters you need to escape in single-quoted stings?

509


How many records can be stored in mysql table?

550


Tell me how can you pass a variable by reference?

509






What is an array in php?

616


How many keywords are there in php?

617


Which of the delimiter is ASP style?

623


What is the use of trim in php?

523


Is nan in javascript?

520


What are the methods to submit form in php?

525


What is the php function that removes the first element of the array and returns it?

510


Is php better than python?

551


Do you know what does $globals means?

557


What is the use of Mbstring?

538