Sorting Arrays
To sort arrays, we can invoke a wide range of functions on our variable $array. The simplest of these is sort(). We’ll use a simpler array this time, to prevent confusion. All the datatypes here are strings, labelled numerically with their string equivalent. See how, in this instance, we’re still assigning each string
value a
key, and the keys are arranged in descending numerical order
PHP Code:
$array = array(4 => "one", 3 => "two", 2 => "three", 1 => "four");
print_r($array);
sort($array);
print_r($array);
This will produce the output
PHP Code:
Array ( [4] => one [3] => two [2] => three [1] => four )
Array ( [0] => four [1] => one [2] => three [3] => two )
But wait, is that not what you expected? The thing to bear in mind here is that the values we’ve assigned to the array entries are
strings. And in this case, the sort() function is sorting the
values in
alphabetical order.
See how in the second line, after the sort() function, the keys have been reset - we now start with the key “0″ and increment the keys for each new value. The default behaviour of arrays in PHP is to assign the value 0 to the first key, not 1 as you might expect.
If we want to maintain the keys in our array though, so that each value is still associated with the key that we assigned it, we can use the asort() function.
PHP Code:
$array = array(4 => "one", 3 => "two", 2 => "three", 1 => "four");
asort($array);
print_r($array);
Will produce the output
PHP Code:
Array ( [1] => four [4] => one [2] => three [3] => two )
But, this might still not be what you’re looking for in a sort function. What if we wanted to sort our array not by the value of each entry, but the
keys associated with each value? Well, in that case we can use the ksort() function
PHP Code:
$array = array(4 => "one", 3 => "two", 2 => "three", 1 => "four");
ksort($array);
print_r($array);
And this produces the output
PHP Code:
Array ( [1] => four [2] => three [3] => two [4] => one )
Multidimensional arrays
Once you start delving deep into the nature of Arrays in PHP, you’ll discover a great deal of complexity hidden beneath the surface. Much of this complexity comes from the fact that arrays can potentially contain other arrays as values too. You can see how this might make things a little harder to visualise!
Sorting Multidimensional Arrays
Consider this example. A delivery service needs to maintain a list of addresses and names where packages are to be sent on a specific day. Along with this information, they also need to assign each delivery a priority number, to ensure that the most important deliveries arrive first.
[php]$customer_1 = array("name" => "Billy Bob", "address" => "1 The Street, Streetsville", "priority" => 3);
$customer_2 = array("name" => "Jim James", "address" => "4 Avenue Road, Roadtown", "priority" => 1);
$customer_3 = array("name" => "Henry Henriksson", "address" => "79 Pavement Lane, Paveston", "priority" => 4);
$customer_4 = array("name" => "Alan Alansson", "address" => "55 Ocean Drive, Ocean City", "priority" => 2);
$deliveries = array($customer_1, $customer_2, $customer_3, $customer_4);
print_r($deliveries);[p/hp]
This will produce the following output (formatted for ease of reading)
PHP Code:
Array (
[0] => Array ( [name] => Billy Bob [address] => 1 The Street, Streetsville [priority] => 3 )
[1] => Array ( [name] => Jim James [address] => 4 Avenue Road, Roadtown [priority] => 1 )
[2] => Array ( [name] => Henry Henriksson [address] => 79 Pavement Lane, Paveston [priority] => 4 )
[3] => Array ( [name] => Alan Alansson [address] => 55 Ocean Drive, Ocean City [priority] => 2 ) )
)
So you can see, the $deliveries array contains, as its values, other arrays, with key values 0, 1 and 2. We now have a data structure containing all the information we need to decide who gets their parcel first. But we can’t base that decision on the order of entries in the array, and we can’t apply any of the sorting mechanisms outlined in the previous tutorial because the information we need to use to decide what the ordering should be is hidden away inside the array values, and PHP doesn’t know that we wish to sort by these values on its own, so what can we do here?
Thankfully, PHP includes a number of useful functions we can use to deal with nasty multidimensional arrays like this, and the one we’re going to use here to solve our problem is called usort()
usort() is used to execute user-defined functions on all the values inside an array. We’ll define a function here, and call it delivery_sort()
PHP Code:
1
2
3
4
5
6
7
8
9
function delivery_sort($a, $b)
{
$priority_a = $a["priority"];
$priority_b = $b["priority"];
if ($priority_a == $priority_b) {
return 0;
}
return ($priority_a < $priority_b) ? -1 : 1;
}
</div> Then, we apply that function to our $delivery array by using the usort function
PHP Code:
usort($deliveries, "delivery_sort");
print_r($deliveries);
This gives us a newly ordered $deliveries array, with the highest priority array listed first
PHP Code:
Array (
[0] => Array ( [name] => Jim James [address] => 4 Avenue Road, Roadtown [priority] => 1 )
[1] => Array ( [name] => Alan Alansson [address] => 55 Ocean Drive, Ocean City [priority] => 2 )
[2] => Array ( [name] => Billy Bob [address] => 1 The Street, Streetsville [priority] => 3 )
[3] => Array ( [name] => Henry Henriksson [address] => 79 Pavement Lane, Paveston [priority] => 4 ) )
Let’s take a step-by-step look at what’s happening here
- Line 1 : the function takes as its parameters, two values $a and $b. usort() will compare each entry in the target array with each other entry using these parameters (e.g. $a = array key 0, $b = array key 1, and then $a = array key 0, $b = array key 2 and so on)
- Lines 3, 4 : within the function, we have access to each of the $customer arrays through the usort() function, and can access the value of “priority”
- Lines 5-8 : the important thing to note about usort is that the values returned determine how the array is to be sorted. If the value of “priority” in $a is less than “priority” in $b in our case, then we return -1. This lets usort() know that $a should be sorted lower than $b. Similary, if they are equal, we return 0, and if greater, we return 1