php array sort alphabetically 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: php sort hight to low

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

Example 4: php array sort

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

Tags:

Php Example