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
| Function | Sorts by | Keeps Keys? |
|---|---|---|
sort() | Values | β No |
asort() | Values | β Yes |
ksort() | Keys | β Yes |
No comments yet! You be the first to comment.
