PHP Array asort() Function (With Examples)

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

PHP asort() function

The asort() function is used to sort an associative array in ascending 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 asort() function:

rsort(array, [mode]);

Parameters

The parameters of the asort() 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 
(     
    [abhi] => 20 
    [radib] => 21
    [amit] => 21 
    [manju] => 25
    [prem] => 27 
)

PHP asort() Function Example

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

print "unsorted array...\n";
print_r($person);
//sorting...

asort($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 
(     
    [abhi] => 20 
    [radib] => 21
    [amit] => 21 
    [manju] => 25
    [prem] => 27 
)  

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.