PHP array_arsort() Function
The PHP `array_arsort()` function sorts an associative array in descending order, according to the value. The keys are maintained while sorting.
Definition
The syntax of `array_arsort()` is as follows:
Syntax
bool array_arsort(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: array_arsort1.php
PHP Example
<?php
$ages = array("Peter" => 35, "Ben" => 37, "Joe" => 43);
array_arsort($ages);
foreach($ages as $key => $value) {
echo "Key: ".$key." Value: ".$value."
";
}
?>
Output
Key: Joe Value: 43
Key: Ben Value: 37
Key: Peter Value: 35
Sorting with Flags
File:array_arsort2.php
PHP Example
<?php
$products = array("Apple" => "20", "Orange" => "10", "Banana" => "15");
array_arsort($products, SORT_NUMERIC);
foreach($products as $key => $value) {
echo "Product: ".$key." Price: ".$value."
";
}
?>
Output
Product: Apple Price: 20
Product: Banana Price: 15
Product: Orange Price: 10