Using PHP's built-in sorting function

PHP has a rich library of predefined functions, and that also includes different sorting functions. It has different functions to sort a list of items in an array either by value or by key/index. We can also keep the association of the array's values with their respective keys while doing the sorting. Another important function of PHP is the built-in function for sorting a multi-dimensional array. Here is a summary of these functions:

Function name

Purpose

sort()

This sorts an array in ascending order. Value/key association is not preserved.

rsort()

Sort an array in reverse/descending order. Index/key association is not preserved.

asort()

Sort an array while maintaining index association.

arsort()

Sort an array in reverse order and maintain index association.

ksort()

Sort an array by key. It maintains key to data correlations. This is useful mainly for associative arrays.

krsort()

Sort an array by key in reverse order.

natsort()

Sort an array using a natural order algorithm, and Value/key association is maintained.

natcasesort()

Sort an array using a case insensitive "natural order" algorithm, and Value/key association is maintained.

usort()

Sort an array by values using a user-defined comparison function, and Value/Key association is not maintained.

The second parameter is a callable function for comparison.

uksort()

Sort an array by keys using a user-defined comparison function, and Value/key association is maintained.

The second parameter is a callable function for comparison.

uasort()

Sort an array by values using a user-defined comparison function, and Value/key association is maintained.

The second parameter is a callable function for comparison.

For sort, rsort, ksort, krsort, asort, and arsort, the following sorting flags are available:

  • SORT_REGULAR: compare items as they are (don't change types)
  • SORT_NUMERIC: compare items numerically
  • SORT_STRING: compare items as strings
  • SORT_LOCALE_STRING: compare items as strings, based on the current locale
  • SORT_NATURAL: compare items as strings using "natural ordering"
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset