Google News
logo
PHP Program to asort() - Sort array in ascending order, according to value
In the following example of PHP program that demonstrates how to use the `asort()` function to sort an associative array in ascending order, according to the value of each element :
Program :
<?php

// Create an associative array of names and ages
$ages = array("Alice" => 25, "Bob" => 30, "Charlie" => 20, "David" => 35);

// Sort the array in ascending order, according to value
asort($ages);

// Loop through the sorted array and print the values
foreach($ages as $name => $age) {
    echo $name . " is " . $age . " years old.<br>";
}

?>
Output :
Charlie is 20 years old.
Alice is 25 years old.
Bob is 30 years old.
David is 35 years old.
In this example, we have created an associative array `$ages` containing the names and ages of some people. We use the `asort()` function to sort the array in ascending order, according to the value of each element.

The sorted array is then looped through using a `foreach` loop and the names and ages of each person are printed to the screen.

The `asort()` function works in a similar way to the `sort()` function, but is used for associative arrays and sorts the elements according to their values instead of their keys.

It modifies the original array in place and returns a boolean value indicating whether the sort was successful or not. If you want to sort the array in descending order, you can use the `arsort()` function instead.