03-Apr-2023
.
Admin
Hi guys,
Today i am explained how to use php array sort by key or value example. This article i am use ksort() function sorts an associative array in ascending order, according to the key. I will help for you in this example php array sort by key value.
This toturial to i am use in ksort() function in this example and show to use in foreach() loop in this example. So my step follow it.
So Let's get started to the example.
Solution
// sort by key
ksort($age);
// sort by value
asort($age);
Sort By Key
This example to use in php array sort by key through. And value through sort to use in ksort() function in php.
Example 1
<?php
$age=array("pranav"=>"35","bolt"=>"37","john"=>"43");
ksort($age);
foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Output
Key=bolt, Value=37
Key=john, Value=43
Key=pranav, Value=35
Sort By Value
This example to use in php array sort by value through. And value through sort to use in asort() function in php.
Example 2
<?php
$age=array("Peter"=>"35","Ben"=>"43","Joe"=>"37");
asort($age);
foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Output
Key=Peter, Value=35
Key=Joe, Value=37
Key=Ben, Value=43
i hope it can help you...
#PHP 8
#PHP