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

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

// Sort the array in ascending order, according to key
ksort($ages);

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

?>
Output :
Alice is 25 years old.
Bob is 30 years old.
Charlie is 20 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 `ksort()` function to sort the array in ascending order, according to the key 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 `ksort()` function works in a similar way to the `sort()` function, but is used for associative arrays and sorts the elements according to their keys instead of their values.

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 `krsort()` function instead.