PHP sort() Function
In this chapter you will learn:
- Definition for PHP sort() Function
- Syntax for PHP sort() Function
- Parameter for PHP sort() Function
- Note for PHP sort() Function
- Example - PHP sort() Function
- Example - Sort the elements of the $numbers array in ascending numerical order
Definition
The sort() function sorts an indexed array in ascending order (alphabetically for letters, numerically for numbers, letters before numbers).
Syntax
PHP sort() Function has the following syntax.
sort(array,sortingtype);
Parameter
Parameter | Is Required | Description |
---|---|---|
array | Required. | Array to sort |
sortingtype | Optional. | How to compare the array elements/items. |
Possible values for sortingtype:
Value | Description |
---|---|
0 = SORT_REGULAR | Default. Compare items normally (don't change types) |
1 = SORT_NUMERIC | Compare items numerically |
2 = SORT_STRING | Compare items as strings |
3 = SORT_LOCALE_STRING | Compare items as strings, based on current locale |
4 = SORT_NATURAL | Compare items as strings using natural ordering |
5 = SORT_FLAG_CASE | an be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively |
Note
The values in the sorted arrays have different keys from the values in the original array.
The sort() and rsort() functions reindex the original array.
Example
<?php// j av a 2 s . c om
$cars=array("A","B","C");
sort($cars);
$authors = array( "Java", "PHP", "CSS", "HTML" );
sort( $authors );
print_r( $authors );
?>
The code above generates the following result.
Example 2
Sort the elements of the $numbers array in ascending numerical order:
<?php
$numbers=array(4,6,2,22,11);
sort($numbers);
?>
Next chapter...
What you will learn in the next chapter:
- Definition for PHP uasort() Function
- Syntax for PHP uasort() Function
- Parameter for PHP uasort() Function
- Example - PHP uasort() Function
Home » PHP Tutorial » PHP Array Functions