How to Use the PHP sort() Function

In this brief tutorial, we will learn how to use PHP’s sort function to sort the values in an array.

A variable is limited by the fact that it can only store one value, whether it be a number or text. This limitation is overcome by the use of an array, which allows you to store multiple values. You can access these values by simply referring to the array, or you can also access specific values or elements in the array, since each has its own index.

As you use PHP, you may find it useful to sort elements in an array into sequences that differ from PHP’s default method (arrays are unsorted lists). This tutorial will show you how to achieve this using the PHP sort() function.

When using the sort() function, elements will be assigned new keys that replace any existing keys. If the function is successful, it will return TRUE.  If it fails, it will return FALSE.

The syntax for the sort() function is as follows:

sort (array, sorttype)

The array parameter identifies the array to sort and is required. 

The sorttype identifies the way in which the array values are to be sorted.  It is optional.  Here are some possible sorttype values:

SORT_REGULAR – this is the default sorttype that will treat values as they are.
SORT_NUMERIC – this sorttype will treat values numerically
SORT_STRING – values in this sorttype will be treated as strings
SORT_LOCALE_STRING – values here will be treated as strings based on local settings

By default, PHP will arrange the elements in an array in alphabetical order. For instance, if you used the code:

<?php
$state_array = array("a" => "Delaware", "b" => "California", "c" => "Hawaii");

sort($state_array);
print_r($state_array);
?>

You result would be something like:

Array
(
[0] => Delaware
[1] => California
[2] => Hawaii

To have the array sorted, you would use the sort() function like so:

<?php
$state_array = array("a" => "Delaware", "b" => "California", "c" => "Hawaii");

sort($state_array);
print_r($state_array);
?>

The preceding code will produce the following output:

Array
(
[0] => California
[1] => Delaware
[2] => Hawaii

{mospagebreak title=PHP Array Sort Function}

Google+ Comments

Google+ Comments