PHP sort() Function

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

  1. SORT_REGULAR(Default) compare items normally (don’t change types)
  2. SORT_NUMERICcompare items numerically
  3. SORT_STRINGcompare items as strings
  4. SORT_LOCALE_STRING – The elements in an array are compared as strings based on the current locale.
  5. SORT_NATURAL – The elements in the array are compared as a string using natural ordering.
  6. 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 RepresentationVisual Representation of PHP sort() Function

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-sensitivelyVisual Representation of 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-insensitivelyVisual Representation of 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.

1 thought on “PHP sort() Function”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.