PHP sort() Function
Topic: PHP Array ReferencePrev|Next
Description
The sort()
function sorts the values of the indexed array in ascending order.
The following table summarizes the technical details of this function.
Return Value: | Returns TRUE on success or FALSE on failure. |
---|---|
Version: | PHP 4+ |
Syntax
The basic syntax of the sort()
function is given with:
The following example shows the sort()
function in action.
Example
Run this code »<?php
// Sample array
$fruits = array("apple", "orange", "mango", "banana", "kiwi");
// Sorting the fruits array alphabetically in ascending order
sort($fruits);
print_r($fruits);
?>
Tip: The counterpart of the sort()
function is the rsort()
function, which is used for sorting the values of the indexed array alphabetically or numerically in descending order.
Parameters
The sort()
function accepts the following parameters.
Parameter | Description |
---|---|
array | Required. Specifies the array to sort. |
sort_flags |
Optional. Specifies how array items should be compared. Possible values are:
|
More Examples
Here're some more examples showing how sort()
function actually works:
The following example sorts an indexed array having numeric values in ascending order:
Example
Run this code »<?php
// Sample array
$numbers = array(2, 5, 10, 8, 15, 13, 20);
// Sorting the numbers array numerically in ascending order
sort($numbers);
print_r($numbers);
?>