Home » PHP

PHP arsort() function with example

PHP arsort() function: Here, we are going to learn about the arsort() function with example in PHP?
Submitted by IncludeHelp, on February 14, 2019

PHP arsort() function

arsort() function is used to sort an associative array in descending order based on the values, as we know that an associative array contains keys and values, this method sorts an array according to the values.

It does not return a sorted array, it sorts the input array.

Syntax:

    arsort(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:
    $person = array(
        "radib" => 21,
        "amit" => 21,
        "abhi" => 20,
        "prem" => 27,
        "manju" => 25
        );

    Output:
    sorted array...  
    Array
    (    
        [prem] => 27 
        [manju] => 25
        [radib] => 21
        [amit] => 21 
        [abhi] => 20 
    )

PHP code:

<?php    
    $person = array(
        "radib" => 21,
        "amit" => 21,
        "abhi" => 20,
        "prem" => 27,
        "manju" => 25
        );

    print ("unsorted array...\n");
    print_r ($person);
    //sorting...
    
    arsort($person);
    print ("sorted array...\n");
    print_r ($person);    
?>

Output

unsorted array...
Array
(    
    [radib] => 21
    [amit] => 21 
    [abhi] => 20 
    [prem] => 27 
    [manju] => 25
)    
sorted array...  
Array
(    
    [prem] => 27 
    [manju] => 25
    [radib] => 21
    [amit] => 21 
    [abhi] => 20 
) 





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.