PHP Array arsort() Function (With Examples)

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

PHP arsort() function

The 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

The syntax of the arsort() function:

arsort(array, [mode]);

Parameters

The parameters of the arsort() 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:
$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 arsort() Function Example

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

The output of the above example is:

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 
) 

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.