PHP Function Reference

PHP sort() Function



The PHP sort() function sorts an array by value in ascending order. The function has one optional parameter which can be used to specify sorting behavior.

Note: This function assigns new keys to the elements in array. It removes any existing keys that may have been assigned, rather than just reordering the keys.

Syntax

sort(array, flags)

Parameters

array Required. Specify the array to sort.
flags Optional. Specify sorting type flags to modify the sorting behavior. Sorting type flags:
  • SORT_REGULAR - Default. Compare items normally.
  • SORT_NUMERIC - Compare items numerically.
  • SORT_STRING - Compare items as strings.
  • SORT_LOCALE_STRING - Compare items as strings, based on current locale.
  • SORT_NATURAL - Compare items as strings using natural ordering.
  • SORT_FLAG_CASE - Compare items as strings and case-insensitive. Can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL.

Return Value

Returns true on success or false on failure.

Exceptions

NA.

Example:

In the example below, sort() function is used to sort an indexed array in ascending order.

<?php
$MyArray = array("Marry", "John", "Jo", "Kim", "Adam");
sort($MyArray);

print_r($MyArray);
?>

The output of the above code will be:

Array
(
    [0] => Adam
    [1] => Jo
    [2] => John
    [3] => Kim
    [4] => Marry
)

Example:

Consider one more example where this function is used to sort an array using case-insensitive natural ordering.

<?php
$MyArray = array("John1", "john2", "John3", "john20");
sort($MyArray, SORT_NATURAL | SORT_FLAG_CASE);

print_r($MyArray);
?>

The output of the above code will be:

Array
(
    [0] => John1
    [1] => john2
    [2] => John3
    [3] => john20
)

❮ PHP Array Reference