array sorting php code example

Example 1: sort array of array php

sort() //sort arrays in ascending order
rsort() //sort arrays in descending order
asort() //sort associative arrays in ascending order, according to the value
ksort() //sort associative arrays in ascending order, according to the key
arsort() //sort associative arrays in descending order, according to the value
krsort() //sort associative arrays in descending order, according to the key
  
//Example
  $array = array(1, 3, 2);
  sort($array) //1, 2, 3

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 sort hight to low

$letters=array("b","a","c");
arsort($letters); //referse sort an array ("c","a","b")

Example 5: php array sort

function aasort (&$array, $key) {
    $sorter=array();
    $ret=array();
    reset($array);
    foreach ($array as $ii => $va) {
        $sorter[$ii]=$va[$key];
    }
    asort($sorter);
    foreach ($sorter as $ii => $va) {
        $ret[$ii]=$array[$ii];
    }
    $array=$ret;
}

aasort($your_array,"order");

Example 6: php array sort

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