- Chapter 3: Using Arrays
- 1 Declaring an Array
- 2 Printing Out an Array
- 3 Eliminating Duplicate Elements
- 4 Enlarging or Shrinking an Array
- 5 Merging Arrays
- 6 Iteratively Processing Elements in an Array
- 7 Accessing the Current Element in an Array
- 8 Accessing Different Areas of an Array
- 9 Searching an Array
- 10 Searching for the Different Elements in Two Arrays
- 11 Randomizing the Elements of an Array
- 12 Determining the Union, Intersection, or Difference Between Two Arrays
- 13 Sorting an Array
- 14 Sorting Sensibly
- 15 Reversing Order
- 16 Perl-Based Array Manipulation Features
3.13 Sorting an Array
You want to sort an entire array by your own function because PHP's functions do not fit your need.
Technique
Use the usort() function to specify a user-defined function for sorting the array:
<?php function cmp_debt($a, $b) { if ($a[1]== $b[1]) return 0; return ($b[1] > $a[1]) ? 1 : -1; } // Suppose you have an array that you use to keep track of // how much your buddies owe you after that game of poker. // You want to sort the array from largest debt to lowest, but // regular sorting functions in PHP can't help. $buddy_debts = array(array("John",31), array("Dave", 12), array("Kris", 15), array("Werner", 38), array("Phil", 9)); usort($buddy_debts, 'cmp_debt'); foreach ($buddy_debts as $buddy_debt) { print $buddy_debt[0]." owes ".$buddy_debt[1]; print "<br>"; } ?>
Comments
The usort() function takes an array and sorts it by a user-defined function; in this case, the function is called cmp_debt(). The function must return -1, 0, or 1. From the PHP manual: "The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. If two members compare as equal, their order in the sorted array is undefined."
We have to resort to using usort() because of the way our $buddy_debts array is structured. PHP's regular sorting functions look only one level deep inside the array, and comparing arrays of arrays is not currently supported.
If you want to use the usort() function without the hassle of declaring an extra sort function, you can use it in conjunction with PHP's create_function() function:
<?php $buddy_debts = array(array("John",31), array("Dave", 12), array("Kris", 15), array("Werner", 38), array("Phil", 9)); usort($buddy_debts, create_function('$a, $b', 'if ($a[1] == $b[1]) return 0; return ($b[1] > $a[1]) ? 1 : -1;'); foreach ($buddy_debts as $buddy_debt) { print $buddy_debt[0]." owes ".$buddy_debt[1]; print "<br>"; } ?>