Difference Between sort() and ksort() in PHP

In PHP, managing arrays often requires sorting their elements in a specific order. This article explains the key differences between the sort() and ksort() functions, illustrating how sort() arranges array elements by value while resetting their keys, whereas ksort() organizes associative arrays by their keys while preserving the original key-value relationships.

Understanding PHP sort()

The sort() function is used to sort the values of an array in ascending order (low to high, alphabetical, or numerical).

The most critical characteristic of sort() is that it does not preserve keys. When you apply sort() to an array, PHP discards any existing keys (whether numeric or associative) and assigns new, zero-based numeric keys to the sorted elements.

Example of sort():

$fruits = ["b" => "banana", "a" => "apple", "c" => "cherry"];
sort($fruits);
print_r($fruits);

Output:

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

As shown above, the original keys (b, a, c) were lost and replaced with 0, 1, and 2.


Understanding PHP ksort()

The ksort() function stands for “key sort.” It is designed to sort an associative array in ascending order by its keys, rather than its values.

Unlike sort(), ksort() preserves the relationship between the keys and their corresponding values. This is essential when working with associative arrays where the key holds meaningful data.

Example of ksort():

$fruits = ["b" => "banana", "a" => "apple", "c" => "cherry"];
ksort($fruits);
print_r($fruits);

Output:

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

Here, the array is ordered alphabetically by the keys (a, then b, then c), and each key retains its original value.


Key Differences Summary

Feature sort() ksort()
Sorted By Values Keys
Key Preservation No (Re-indexes array with numbers starting at 0) Yes (Preserves existing keys and relationships)
Primary Use Case Simple indexed arrays where keys do not matter Associative arrays where keys are meaningful
Sorting Order Ascending Ascending

Choosing between these two functions depends entirely on whether your array keys need to be preserved and whether you want to sort by the data values or the identifiers (keys) of that data.