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
)





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.