array sort by value php code example
Example 1: sort array of array php
sort()
rsort()
asort()
ksort()
arsort()
krsort()
$array = array(1, 3, 2);
sort($array)
Example 2: php sort by associative array value
usort($inventory, function ($item1, $item2) {
return $item1['price'] <=> $item2['price'];
});
Example 3: php store sorted array
$array = array();
$sorted_array = $array;
asort($sorted_array);
Example 4: sort array php
<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
asort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>
//Would output:
c = apple
b = banana
d = lemon
a = orange
Example 5: array sort php
<?php
$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
echo $val;
}
?>
Example 6: php array sort by key value
To PHP sort array by key, you should use:
ksort() (for ascending order) or krsort() (for descending order).
To PHP sort array by value, you will need functions:
asort() and arsort() (for ascending and descending orders).