Functions for sorting arrays

sort($array[, $compare])
rsort($array[, $compare])
asort($array[, $compare])
arsort($array[, $compare])
ksort($array[, $compare])
krsort($array[, $compare])

How to sort strings in ascending order

$names = array('Mike', 'Anne', 'Joel', 'Ray', 'Pren');
sort($names);

How to sort numbers in ascending order

$numbers = array(520, '33', 9, '199');
sort($numbers, SORT_NUMERIC);

How to sort in descending order

$names = array('Mike', 'Anne', 'Joel', 'Ray', 'Pren');
rsort($names);

How to sort an associative array

$tax_rates = array('NC' => 7.75, 'NY' => 8.875, 'CA' => 8.25);
asort($tax_rates); // sorts by value (ascending)
ksort($tax_rates); // sorts by key (ascending)
arsort($tax_rates); // sorts by value (descending)
krsort($tax_rates); // sorts by key (descending)

Back