An array can be sorted in different ways, so there are a lot of chances that the order that we need is different from the current one. By default, the array is sorted by the order in which the elements were added to it, but we can sort an array by its key or by its value, both ascending and descending.
Furthermore, when sorting an array by its values, you can choose to preserve their keys or to generate new ones as a list
There is a complete list of these functions on the official documentation website at http://php.net/manual/en/array.sorting.php, but here we will display the most important ones:
These functions always take one argument, the array, and they do not return anything. Instead, they directly sort the array we pass to them. Let’s see some of the examples:
<?php $properties = [ 'firstname' => 'Tom', 'surname' => 'Riddle', 'house' => 'Slytherin' ]; $properties1 = $properties2 = $properties3 = $properties; sort($properties1); var_dump($properties1); asort($properties3); var_dump($properties3); ksort($properties2); var_dump($properties2);
In the last example, First of all, we initialize an array with some key values and assign it to $properties. Then we create three variables that are copies of the original array—the syntax should be intuitive.
Why do we do that? Because if we sort the original array, we will not have the original content any more. This is not what we want in this specific example, as we want to see how the different sort functions affect the same array.
Finally, we perform three different sorts, and print each of the results. The browser should show we something like
the following:
array(3) { [0]=> string(6) "Riddle" [1]=> string(9) "Slytherin" [2]=> string(3) "Tom" } array(3) { ["surname"]=> string(6) "Riddle" ["house"]=> string(9) "Slytherin" ["firstname"]=> string(3) "Tom" } array(3) { ["firstname"]=> string(3) "Tom" ["house"]=> string(9) "Slytherin" ["surname"]=> string(6) "Riddle" }
The first function, sort, orders the values alphabetically. Also, if we check the keys, now they are numeric as in a list, instead of the original keys. Instead, asort orders the values in the same way, but keeps the association of key-values.
Finally, ksort orders the elements by their keys, alphabetically.