sqltreat
answered Feb 27 '23 00:00
To sort an array by array key in PHP, you can use the ksort() or krsort() function. These functions sort the array by its keys in ascending or descending order , respectively.
Here's an example of how to use ksort() to sort an array by its keys in ascending order:
$fruits = array(
'banana' => 3,
'apple' => 5,
'orange' => 2,
'kiwi' => 4
);
ksort($fruits);
foreach ($fruits as $fruit => $count) {
echo $fruit . ': ' . $count . '<br>';
}
In this example, we have an array called $fruits with four elements, where each key is a fruit name and each value is the count of that fruit. We use the ksort() function to sort the array by its keys in ascending order .
We then loop through the sorted array using a foreach loop and output each element using the echo statement.
The output of this code will be:
apple: 5
banana: 3
kiwi: 4
orange: 2
If you want to sort the array by its keys in descending order , you can use the krsort() function instead of ksort() . The usage of krsort() is similar to ksort(), but it sorts the array by its keys in descending order instead of ascending order.