General Array Sorting in PHP
PHP offers several array sorting functions. These array sorting functions sort array values only ( “sort
” ), rearrange array values by sorting the array key ( “ksort
” ), or rearranging array keys by sorting the array values ( “asort
” ). Reverse sort functions rsort
, krsort
, and arsort
are also available. In addition to these simple sort functions, PHP provides corresponding versions of these sorting functions that use user-defined comparators. This is useful when an array is populated with user-defined types. An example of using uasort, a version of asort that uses a user-defined comparator, is given below.
<?php
function nameComparator( $a, $b )
{
$field = "Name";
if( $a[$field] == $b[$field] )
return 0;
else
return $a[$field] > $b[$field] ? 1 : -1;
}
function classComparator( $a, $b )
{
$field = "Class";
if( $a[$field] == $b[$field] )
return 0;
else
return $a[$field] > $b[$field] ? 1 : -1;
}
$a[] = array( "Name" => "Steve", "Class" => "A" );
$a[] = array( "Name" => "Jennifer", "Class" => "B" );
uasort( $a, "nameComparator" );
print_r( $a );
uasort( $a, "classComparator" );
print_r( $a );
?>
The sort functions that use user-defined comparators are more flexible than the simple sort functions. The sorts that use user-defined comparators may be stable, where the original ordering is preserved in cases of ties. This behavior can be altered by handling ties explicitly in the comparator. The PHP array sorting functions that use user-defined comparators are great examples of function callbacks and the Strategy pattern.