sort php array by value code example

Example 1: php store sorted array

$array = array();
$sorted_array = $array;
asort($sorted_array);

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: array sort php

<?php

$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
    echo $val;
}
/*
OUTPUT:
apple
banana
lemon
orange
*/
?>

Example 4: php array sort

// Fonction de comparaison
function cmp($a, $b) {
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}