PHP Array sort() Function (With Examples)

In this tutorial, we will learn about the PHP sort() function with its usage, syntax, parameters, return value, and examples. By IncludeHelp Last updated : December 31, 2023

PHP sort() Function

The 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

The syntax of the sort() function:

sort(array, [mode]);

Parameters

The parameters of the sort() function:

  • 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)

Return Value

The return type of this method is true, it always returns true.

Sample Input/Output

Input:
$arr1 = array(105, 108, 101, 100, 90);

Output:
arr1 (sorted)...
Array
(    
    [0] => 90   
    [1] => 100  
    [2] => 101  
    [3] => 105  
    [4] => 108  
)

PHP sort() Function Example

<?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

The output of the above example is:

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
)

To understand the above example, you should have the basic knowledge of the following PHP topics:

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.