HomePHPWhat is the difference between sort(), asort(), and ksort()?

What is the difference between sort(), asort(), and ksort()?

🔹 sort()

  • What it does: Sorts an array by values in ascending order.
  • Effect on keys: Keys are reset (reindexed) numerically starting from 0.
  • Use case: When you only care about values and don’t need original keys.
$fruits = ["d" => "banana", "a" => "apple", "c" => "cherry"];
sort($fruits);
print_r($fruits);

Output:

Array
(
    [0] => apple
    [1] => banana
    [2] => cherry
)

➡ Keys (d, a, c) are lost.


🔹 asort()

  • What it does: Sorts an array by values in ascending order.
  • Effect on keys: Keys are preserved.
  • Use case: When you want to sort by values but keep the association between keys and values.
$fruits = ["d" => "banana", "a" => "apple", "c" => "cherry"];
asort($fruits);
print_r($fruits);

Output:

Array
(
    [a] => apple
    [d] => banana
    [c] => cherry
)

➡ Keys are preserved.


🔹 ksort()

  • What it does: Sorts an array by keys in ascending order.
  • Effect on values: Values stay tied to their keys.
  • Use case: When you want to order an associative array alphabetically or numerically by keys.
$fruits = ["d" => "banana", "a" => "apple", "c" => "cherry"];
ksort($fruits);
print_r($fruits);

Output:

Array
(
    [a] => apple
    [c] => cherry
    [d] => banana
)

➡ Sorted by keys (a, c, d).


✅ Quick Comparison Table

FunctionSorts byKeeps Keys?
sort()Values❌ No
asort()Values✅ Yes
ksort()Keys✅ Yes

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *