Web Development

Use the power of these PHP functions to sort your arrays


This article is also available as a TechRepublic download.

If you've worked with PHP over any length of time, you'll already be familiar with arrays -- data structures that allow you to store multiple values in a single variable and operate on them as a set. Often, developers find it useful to sort these values, or array elements, into a sequence different from the default one used by PHP. To this end, PHP offers a wide variety of array sorting functions, which allow you to manipulate the arrangement of elements inside an array and re-sort them in a number of different ways. This tutorial will discuss some of the more important functions in this category.

Simple sorting

To begin, let's consider the most simple case: simple sorting of an array's elements from lowest to highest, either numerically or alphabetically. The PHP function to accomplish this is sort(), demonstrated in Listing A.

Listing A

<?php

$data = array(5,8,1,7,2);

sort($data); print_r($data);

?>

Here's the output:

Array ([0] => 1

[1] => 2

[2] => 5

[3] => 7

[4] => 8

)

It's also possible to reverse the simple sort demonstrated previously, with the rsort() function. This function rearranges an array's elements from highest to lowest, either numerically or alphabetically. Listing B shows you an example.

Listing B

<?php $data = array(5,8,1,7,2);rsort($data); print_r($data);

?>

And here's the output:

Array ([0] => 8

[1] => 7

[2] => 5

[3] => 2

[4] => 1

)

Sorting by key

When working with associative arrays, it's often useful to re-sort the array by keys, again from highest to lowest. The ksort() function is designed for just this task; it maintains the key-value correlation during the sorting process. An example is presented in Listing C.

Listing C

<?php $data = array("US" => "United States", "IN" => "India", "DE" => "Germany", "ES" => "Spain");ksort($data); print_r($data);

?>

And here's the output:

Array ([DE] => Germany

[ES] => Spain

[IN] => India

[US] => United States

)

You can also reverse-sort by key with the krsort() function, which is illustrated in Listing D.

Listing D

<?php $data = array("US" => "United States", "IN" => "India", "DE" => "Germany", "ES" => "Spain");krsort($data); print_r($data);

?>

Here's the output:

Array ([US] => United States

[IN] => India

[ES] => Spain

[DE] => Germany

)

Sorting by value

If, instead, you'd prefer to sort your associative array by value instead of key, PHP's got you covered there too. Simply use the asort() function instead of the aforementioned ksort() function, and you're good to go! Listing E shows you how.

Listing E

<?php $data = array("US" => "United States", "IN" => "India", "DE" => "Germany", "ES" => "Spain");asort($data); print_r($data);

?>

Here's the output. Notice the difference between this and the output of ksort() above -- in both cases, the sorting is alphabetic, but the sorting has been performed on different fields of the array. Notice also that the key-value association is maintained throughout; it's only the manner in which the key-value pairs are ordered that has changed.

Array ([DE] => Germany

[IN] => India

[ES] => Spain

[US] => United States

)

As you will have guessed by now, this sort can also be accomplished in reverse, with a call to arsort(). Listing F shows you an example.

Listing F

<?php $data = array("US" => "United States", "IN" => "India", "DE" => "Germany", "ES" => "Spain");arsort($data); print_r($data);

?>

And here's the output, with the values sorted in reverse-alphabetical order. Again, compare it with the output of krsort() to better understand the difference.

Array ([US] => United States

[ES] => Spain

[IN] => India

[DE] => Germany

)

Natural-language sorting

PHP also has the unique ability to sort arrays the way humans would, using cognitive rather than computational rules. This feature is referred to as natural-language sorting, and it's very useful when building fuzzy-logic applications. To see it in action, consider the simple example shown in Listing G.

Listing G

<?php $data = array("book-1", "book-10", "book-100", "book-5"); sort($data);print_r($data);

natsort($data); print_r($data);?>

Here's the output:

Array ([0] => book-1

[1] => book-10

[2] => book-100

[3] => book-5

)

Array

(

[0] => book-1

[3] => book-5

[1] => book-10

[2] => book-100

)

The difference should be clear: The second sort order is more intuitive and "human," while the first one is more algorithmic and "computational."

Reverse natural-language sorting? Sure! Just use the array_reverse() function on the output of natsort(), as shown in Listing H.

Listing H

<?php $data = array("book-1", "book-10", "book-100", "book-5");natsort($data); print_r(array_reverse($data));

?>

And here's the output:

Array ([0] => book-100

[1] => book-10

[2] => book-5

[3] => book-1

)

Sorting by user-defined rules

PHP also lets you define your own sorting algorithm by creating your own comparison function and passing it to the usort() function. The comparison function must return a number less than 0 if the first argument is to be considered "less" than the second, and a number greater than 0 if the first argument is to be considered "greater" than the second.

Listing I shows an example, which sorts array elements by their length, with the shortest items first:

Listing I

<?php $data = array("joe@host.com", "john.doe@gh.co.uk", "asmithsonian@us.info", "jay@zoo.tw");usort($data, 'sortByLen');

print_r($data); function sortByLen($a, $b) {

if (strlen($a) == strlen($b)) {

return 0;

} else {

return (strlen($a) > strlen($b)) ? 1 : -1;

}

}

?>

In this case, I've created my own comparison function, which uses the strlen() function to compare the number of characters in each string and return a value of 1, 0 or -1, respectively. This return value then forms the basis for deciding the arrangement of elements. Here's the output:

Array ([0] => jay@zoo.tw

[1] => joe@host.com

[2] => john.doe@gh.co.uk

[3] => asmithsonian@us.info

)

Multidimensional sorting

Finally, PHP also lets you perform some fairly complex sorting on multidimensional arrays -- for example, ordering a set of nested arrays first by one common key and then by another. This is similar to using SQL's ORDER BY clause on multiple fields to order data sets in a particular way. To see how this works, take a look at the example shown in Listing J.

Listing J

<?php $data = array(array("id" => 1, "name" => "Boney M", "rating" => 3),

array("id" => 2, "name" => "Take That", "rating" => 1),

array("id" => 3, "name" => "The Killers", "rating" => 4),

array("id" => 4, "name" => "Lusain", "rating" => 3),

); foreach ($data as $key => $value) {

$name[$key] = $value['name'];

$rating[$key] = $value['rating'];

}

array_multisort($rating, $name, $data); print_r($data);?>

Here, I've simulated a data set of rows and columns in the $data array. I've then used the array_multisort() function to re-sort the data set, first by rating and then, in cases where ratings are equal, by name. The output is as follows:

Array ([0] => Array

(

[id] => 2

[name] => Take That

[rating] => 1

) [1] => Array

(

[id] => 1

[name] => Boney M

[rating] => 3

)

[2] => Array

(

[id] => 4

[name] => Lusain

[rating] => 3

)

[3] => Array

(

[id] => 3

[name] => The Killers

[rating] => 4

)

)

This array_multisort() function is one of the most powerful sorting functions available in PHP and has a variety of uses. In addition to what you saw in the example, it can be used to sort multiple independent arrays, using elements of one as the basis for sorting the next, and it can be used to sort database result sets.

The examples should have given you insight into the various array sorting functions available in PHP and showed you some of the power hidden inside PHP's array manipulation toolkit. Happy coding!

0 comments

Editor's Picks