How to make sorting in PHP

Learn how to sort data in php w/ an example: use the array_multisort() function to organize & order your data quickly & easily.

Sorting in PHP

In PHP, sorting arrays is a common task. There are various built-in functions that can be used to achieve this, as well as user-defined functions. This tutorial will focus on the built-in functions.

Sorting Arrays Alphabetically

The most basic sorting function is sort(), which sorts an array into alphabetical order. The syntax is as follows:

sort($array);

For example, if you had an array of names:

$names = array("John", "Bob", "Adam", "Zoe");

You could sort the array alphabetically with:

sort($names);

This would result in an array like this:

Array
(
    [0] => Adam
    [1] => Bob
    [2] => John
    [3] => Zoe
)

Sorting Arrays by Value

The asort() function sorts an array by its values, rather than its keys. The syntax is as follows:

asort($array);

For example, if you had an array of numbers:

$numbers = array(4, 2, 7, 3);

You could sort the array according to value with:

asort($numbers);

This would result in an array like this:

Array
(
    [0] => 2
    [1] => 3
    [2] => 4
    [3] => 7
)

Sorting Arrays by Key

The ksort() function sorts an array by its keys, rather than its values. The syntax is as follows:

ksort($array);

For example, if you had an array of numbers:

$numbers = array("a" => 4, "b" => 2, "c" => 7, "d" => 3);

You could sort the array according to key with:

ksort($numbers);

This would result in an array like this:

Array
(
    [a] => 4
    [b] => 2
    [c] => 7
    [d] => 3
)

Conclusion

These are just a few of the built-in functions that can be used to sort arrays in PHP. There are many more functions available, as well as user-defined functions that can be used to sort array elements. For more information, please refer to the PHP manual.

Answers (0)