PHP provides multiple built-in array sorting functions that help arrange array elements in ascending or descending order. These functions can sort indexed arrays, associative arrays, or arrays based on keys or values.
sort() – Sorts indexed arrays in ascending orderrsort() – Sorts indexed arrays in descending orderasort() – Sorts associative arrays by value (ascending)arsort() – Sorts associative arrays by value (descending)ksort() – Sorts associative arrays by key (ascending)krsort() – Sorts associative arrays by key (descending)Array sorting functions directly modify the original array. Some functions reindex numeric keys, while others preserve key-value relationships. Choosing the correct function depends on whether the array is indexed or associative.
// Sorting an indexed array in ascending order
The sort() function arranges numeric values in ascending order and resets the array indexes starting from zero.
// Sorting an associative array by values while keeping keys
25, "Jane" => 28, "Doe" => 22);
asort($ages);
print_r($ages);
?>
The asort() function sorts array values in ascending order while preserving their corresponding keys.
// Sorting an associative array by keys alphabetically
25, "name" => "John", "city" => "New York");
ksort($person);
print_r($person);
?>
The ksort() function sorts the array based on keys in alphabetical order.
Select a function to see how it transforms the data below.
sort() and rsort() only for indexed arraysasort() or ksort() when key preservation mattersrsort()krsort()