PHP sort() Function

Example

Sort the elements of the array $cars in alphabetical order:

<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
?>

Run Instance

Definition and Usage

The sort() function sorts the index array in ascending order.

Note:This function assigns new key names to the elements of an array. The original key names will be deleted.

Returns TRUE if successful, otherwise FALSE.

Tip:Please use rsort() The function sorts the indexed array in descending order.

Syntax

sort(array,sortingtype);
Parameters Description
array Required. Specifies the array to be sorted.
sortingtype

Optional. Specifies how to compare the elements/items of the array. Possible values:

  • 0 = SORT_REGULAR - Default. Arrange each item in the regular order (Standard ASCII, do not change type)
  • 1 = SORT_NUMERIC - Treat each item as a number.
  • 2 = SORT_STRING - Treat each item as a string.
  • 3 = SORT_LOCALE_STRING - Treat each item as a string, based on the current locale setting (can be changed by setlocale()).
  • 4 = SORT_NATURAL - Treat each item as a string, using a natural sorting similar to natsort().
  • 5 = SORT_FLAG_CASE - Can combine (bitwise OR) SORT_STRING or SORT_NATURAL to sort strings without case sensitivity.

Technical Details

Return Value: Returns TRUE if successful, FALSE otherwise.
PHP Version: 4+

More Examples

Example 1

Sort the elements of the array $numbers in ascending order by number:

<?php
$numbers=array(4,6,2,22,11);
sort($numbers);
?>

Run Instance