sort array desc php code example

Example 1: php sort by associative array value

//php 7+
usort($inventory, function ($item1, $item2) {
    return $item1['price'] <=> $item2['price'];
});

Example 2: 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 3: php sort()

<?php

$fruits = array("Zitrone", "Orange", "Banane", "Apfel");
sort($fruits);
foreach ($fruits as $key => $val) {
    echo "fruits[" . $key . "] = " . $val . "\n";
}

?>

Tags:

Sql Example