PHP array_asort() Function

The PHP `array_asort()` function sorts an associative array in ascending order, according to the value. The keys are maintained while sorting.

Definition

The syntax of `array_asort()` is as follows:

Syntax


bool array_asort(array &$array, int $flags = SORT_REGULAR)
                    
  • $array: The input array to sort.
  • $flags (optional): You can modify the sorting behavior using these flags:
    • SORT_REGULAR: Compare items normally (default).
    • SORT_NUMERIC: Compare items numerically.
    • SORT_STRING: Compare items as strings.
    • SORT_NATURAL: Compare items using "natural order".
    • SORT_FLAG_CASE: Used with `SORT_STRING` for case-insensitive string comparisons.
  • File: code>array_asort1.php

    PHP Example

    
    <?php    
    $ages = array("Peter" => 35, "Ben" => 37, "Joe" => 43);  
    array_asort($ages);  
    foreach($ages as $key => $value) {  
        echo "Key: ".$key." Value: ".$value."
    "; } ?>

    Output

    Key: Peter Value: 35
    Key: Ben Value: 37
    Key: Joe Value: 43

    Sorting with Flags

    File: array_asort2.php

    PHP Example

    
    <?php    
    $products = array("Apple" => "20", "Orange" => "10", "Banana" => "15");  
    array_asort($products, SORT_NUMERIC);  
    foreach($products as $key => $value) {  
    echo "Product: ".$key." Price: ".$value."<br/>";  
    }  
    ?>  
    

    Output

    Product: Orange Price: 10
    Product: Banana Price: 15
    Product: Apple Price: 20