#native_company# #native_desc#
#native_cta#

Sorting Arrays

By Brett Patterson
on June 27, 2005

So now you have an array of information, but you want to sort it alphabetically. Luckily, PHP has built-in functions to do just this. There are many that are available, so I’ll just breeze through the basics of them. You can find lots of info about the sorting of arrays at PHP.net.
sort()
The sort() function just sorts the array. So if we have:

$companies = array(“Microsoft”, “HP”, “Apple”, “Dell”, “Creative”);
sort($companies);
print_r($companies);

Will output:

Array
(
    [0] => Apple
    [1] => Creative
    [2] => Dell
    [3] => HP
    [4] => Microsoft
)

rsort()
This does the same as sort(), except in reverse. So:

$companies = array(“Microsoft”, “HP”, “Apple”, “Dell”, “Creative”);
rsort($companies);
print_r($companies);

Will Output:

Array
(
    [0] => Microsoft
    [1] => HP
    [2] => Dell
    [3] => Creative
    [4] => Apple
)

asort() and arsort()
These sort arrays keep the index intact. asort() sorts normally, and arsort() sorts in reverse. Here’s the code and the output:

$companies = array(“Microsoft”, “HP”, “Apple”, “Dell”, “Creative”);
asort($companies);
print_r($companies);

echo ‘<br>’;

$companies = array(“Microsoft”, “HP”, “Apple”, “Dell”, “Creative”);
arsort($companies);
print_r($companies);

This will output:

Array
(
    [2] => Apple
    [4] => Creative
    [3] => Dell
    [1] => HP
    [0] => Microsoft
)

Array
(
    [0] => Microsoft
    [1] => HP
    [3] => Dell
    [4] => Creative
    [2] => Apple
)

ksort()
This will sort an array by its key. So we’ll modify our original code to be:

$companies = array(“F”=>”Microsoft”, “K”=>”HP”, “A”=>”Apple”, “Z”=>”Dell”, “Q”=>”Creative”);
ksort($companies);
print_r($companies);

Will output:

Array
(
    [A] => Apple
    [F] => Microsoft
    [K] => HP
    [Q] => Creative
    [Z] => Dell
)

That’s all there is to sorting arrays!! Now you can get more and more complex with them, but I just showed you the basics of sorting the arrays in ascending and descending order. As always, reference the online PHP manual at PHP.net if you need more in-depth instructions as to exactly what parameters you can add to the sort functions, or for additional sort functions.

1
|
2
|
3
|
4
|
5