PHP sort() function is “used to sort an array in ascending order.”
Syntax
sort($array, sorttype)
Parameters
$array($required): It specifies the array to sort.
sorttype(optional): There are 6 sorting types which are described below
- SORT_REGULAR(Default) – compare items normally (don’t change types)
- SORT_NUMERIC – compare items numerically
- SORT_STRING – compare items as strings
- SORT_LOCALE_STRING – The elements in an array are compared as strings based on the current locale.
- SORT_NATURAL – The elements in the array are compared as a string using natural ordering.
- SORT_FLAG_CASE – The elements in the array are compared as strings. The elements are treated as case-insensitive and then compared. It can be used with | (bitwise operator) with the SORT_NATURAL or SORT_STRING.
Return value
It returns true(PHP 8.2.0), previously it returned bool.
Visual Representation
Example 1: How to Use sort() Function
<?php
$numbers = [21, 11, 19, 29, 46];
echo 'Before Sort';
print_r($numbers);
sort($numbers);
echo 'After Sort';
print_r($numbers);
Output
Before SortArray
(
[0] => 21
[1] => 11
[2] => 19
[3] => 29
[4] => 46
)
After SortArray
(
[0] => 11
[1] => 19
[2] => 21
[3] => 29
[4] => 46
)
This output shows the array has been sorted in ascending numerical order.
Example 2: sort the string case-sensitively
<?php
$arr = ["Millie", "Finn", "Gaten", "caleb", "noah"];
sort($arr, SORT_STRING);
print_r($arr);
Output
Array
(
[0] => Finn
[1] => Gaten
[2] => Millie
[3] => caleb
[4] => noah
)
In this example, we use the SORT_STRING flag, which specifies that the array should be sorted as strings. This means uppercase letters come before any lowercase letters because of their ASCII values.
Example 3: sort the string case-insensitively
<?php
$arr = ["Millie", "Finn", "Gaten", "caleb", "noah"];
sort($arr, SORT_STRING | SORT_FLAG_CASE);
print_r($arr);
Output
Array
(
[0] => caleb
[1] => Finn
[2] => Gaten
[3] => Millie
[4] => noah
)
In this example, $arr are sorted alphabetically, ignoring the case of the letters. Notice that ‘caleb‘ comes before ‘Finn‘ despite the ‘c’ being lowercase, because SORT_FLAG_CASE causes the comparison to be case-insensitive.
That’s it for this tutorial.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
I really appreciate your straightforward and well-organized instructions. Thank you!