// Print out the result
foreach ($names as $index => $name)
echo('['.$index.']'.$name.' ');
// Which gives [second]Dick [third]Harry [first]Tom
?>
Note: . Although asort() and arsort() can be used on numbered arrays, PHP treats the indexes as keys and maintains the association of the keys with the values of the elements.
This means that the indexes won't run in order as you might expect.
Sorting by Key
The ksort() and krsort() functions work in the same way as asort() and arsort() except that the array is sorted by key instead of by element value.
// Print out the result
foreach ($names as $index => $name)
echo('['.$index.']'.$name.' ');
// Which gives [first]Tom [last]Harry [next]Dick
?>
User-Defined Sorting
This requires a knowledge of functions, which is covered in the tutorial User Defined Functions.
PHP provides three functions to allow user-defined sorting.
usort() which sorts the array based on the value of each element.
uasort() which does the same but preserves the association between the element value and key.
uksort() which sorts the array based on the key rather than the value of each element.
The syntax of all three functions takes the form usort ($array, cmp_function) where cmp_function is the name of a user-defined function that compares two arguments (either element values or keys) to decide if they are equal, one is greater than the other or one is less the other.
The user-defined function is not called directly from within the script but its name passed as a parameter to the sort function. Functions used in this way are normally known as callback functions.
The function can be used to make any comparison you choose. Below is an example that compares the length of two strings and returns 0 if they're equal, 1 if the first is greater than the second and -1 if the first is less than the second.
Example of a Callback Function
<?php
function compare_names ($name1, $name2)
{
if (strlen ($name1) > strlen ($name2)) return 1;
if (strlen ($name1) < strlen ($name2)) return -1;
return 0;
}
?>
The function above can now be used to sort an array of names by their length.