Functions for sorting arrays
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)
- The sorting functions don’t return an array. Instead, they modify the array that’s passed to them.
- The $compare parameter works the same for all sorting functions.A stack is a special type of array that implements a last-in, first-out (LIFO) collec-tion of values. You can use the array_push() and array_pop() functions to add and remove elements in a stack.
-
Back