Home »
PHP
PHP sort() function with example
PHP sort() function: Here, we are going to learn about the sort() function with example in PHP?
Submitted by IncludeHelp, on February 14, 2019
PHP sort() function
sort() function is used to sort an indexed array in ascending order.
If array elements are numeric, it sorts based on the numbers, if array elements are the string, it sorts based on the alphabets and if the array contains numeric values and text/strings, it sorts elements based on the alphabets.
It does not return a sorted array, it sorts the input array.
Syntax:
sort(array, [mode]);
Here,
- array is an input array
-
mode is an optional parameter, its default value is 0, it has following values:
0 – It is used to compare items normally
1 – It is used to compare items numerically
2 – It is used to compare items as strings
3 – It is used to compare items as current locale strings
4 – It is used to compare items as strings (natural ordering)
Examples:
Input:
$arr1 = array(105, 108, 101, 100, 90);
Output:
arr1 (sorted)...
Array
(
[0] => 90
[1] => 100
[2] => 101
[3] => 105
[4] => 108
)
PHP code:
<?php
$arr1 = array(105, 108, 101, 100, 90);
$arr2 = array("Amit", "Prem", "Prerana", "Aleesha", "Abhishek");
sort($arr1);
print ("arr1 (sorted)...\n");
print_r ($arr1);
sort($arr2);
print ("arr2 (sorted)...\n");
print_r ($arr2);
?>
Output
arr1 (sorted)...
Array
(
[0] => 90
[1] => 100
[2] => 101
[3] => 105
[4] => 108
)
arr2 (sorted)...
Array
(
[0] => Abhishek
[1] => Aleesha
[2] => Amit
[3] => Prem
[4] => Prerana
)