CodingBison

This page presents discusses array-based functions that sort arrays (both indexed and associative). We present these functions in three sets. The first set focuses on sorting indexed arrays. The second set focuses on sorting associative arrays using both values and keys. The third set focuses on sorting both indexed and associative arrays by passing a user-defined comparison function.

Sorting Indexed Arrays

The first set discusses functions that sort indexed arrays: sort(), rsort(), natsort(), and natcasesort(). These functions do an in-place sorting of arrays that is they passed the sort array itself and do not return a new array.

 /* These functions do not return a new array and simply sort the passed array */
 sort($passed_indexed_array)
 rsort($passed_indexed_array) 
 natsort($passed_indexed_array) 
 natcasesort($passed_indexed_array)
 multisort($passed_indexed_array1, $passed_indexed_array2, ...)

Let us describe these functions.

sort() sorts an array in ascending order (for numbers, it is increasing order and for strings, it is the order in which they would appear in a dictionary).

rsort() sorts an array in descending order.

natsort() sorts an array in natural order and is used when array elements have both alphabets and numbers. Natural ordering takes into account both numeric and string parts of a variable. Thus, with natural ordering, "user_200.txt" is less than "user_1000.txt" because after the common string "user_", the number 200 is less than 1000.

natcasesort() is merely a case-insensitive variant of natsort().

array_multisort() sorts multiple arrays in one step and yet maintains alignment for elements based on the initial index. In other words, if the first elements of multiple arrays refer to different properties of the same object and if the first element of the first array is moved to a new index, then the first elements of other arrays are also moved to the same new index -- this way, these elements remain aligned with each other.

Let us begin with a examples that provides usage of these functions. Our first example shows implementations based on sort() and rsort().

 <?php
 $array_user = array("J Fulton", "K Simon", "M Simpson", "A Moore");
 echo "Before sorting, array_user: <br>";
 print_r($array_user);

 sort($array_user);
 echo "<br><br> After sorting, array_user: <br>";
 print_r($array_user);

 rsort($array_user);
 echo "<br><br> After reverse sorting, array_user: <br>";
 print_r($array_user);
 ?>

And, here is the output:

 Before sorting, array_user:
 Array ( [0] => J Fulton [1] => K Simon [2] => M Simpson [3] => A Moore )

 After sorting, array_user:
 Array ( [0] => A Moore [1] => J Fulton [2] => K Simon [3] => M Simpson )

 After reverse sorting, array_user:
 Array ( [0] => M Simpson [1] => K Simon [2] => J Fulton [3] => A Moore )

Our next example motivates the need to have natural sorting when array elements contain both numbers and alphabets.

 <?php
 $array_userid = array("jfulton35", "jfulton1", "jfulton100", "jfulton20");
 echo "<br><br> Before sorting, array_userid: <br>";
 print_r($array_userid);

 sort($array_userid);
 echo "<br><br> After sorting, the array_userid: <br>";
 print_r($array_userid);

 natsort($array_userid);
 echo "<br><br> After natural sorting, the array_userid: <br>";
 print_r($array_userid);

 $array_userid_mixedcase = array("Jfulton35", "jfUlton1", "jfuLton100", "jfulTon20");
 echo "<br><br> The new array_userid_mixedcase: <br>";
 print_r($array_userid_mixedcase);

 natsort($array_userid_mixedcase);
 echo "<br><br> After natural sorting, the array_userid_mixedcase is: <br>";
 print_r($array_userid_mixedcase);

 natcasesort($array_userid_mixedcase);
 echo "<br><br> After natural case sorting, the array_userid_mixedcase is: <br>";
 print_r($array_userid_mixedcase);
 ?>

The output (provided below) shows that when we call sort() on array $array_userid, the output is ("jfulton1", "jfulton100", "jfulton20", "jfulton35"). This output is not in natural order. However, when we call natsort(), the output (as intended) becomes ("jfulton1", "jfulton20", "jfulton35", "jfulton100").

 Before sorting, array_userid:
 Array ( [0] => jfulton35 [1] => jfulton1 [2] => jfulton100 [3] => jfulton20 )

 After sorting, the array_userid:
 Array ( [0] => jfulton1 [1] => jfulton100 [2] => jfulton20 [3] => jfulton35 )

 After natural sorting, the array_userid:
 Array ( [0] => jfulton1 [2] => jfulton20 [3] => jfulton35 [1] => jfulton100 )

 The new array_userid_mixedcase:
 Array ( [0] => Jfulton35 [1] => jfUlton1 [2] => jfuLton100 [3] => jfulTon20 )

 After natural sorting, the array_userid_mixedcase is:
 Array ( [0] => Jfulton35 [1] => jfUlton1 [2] => jfuLton100 [3] => jfulTon20 )

 After natural case sorting, the array_userid_mixedcase is:
 Array ( [1] => jfUlton1 [3] => jfulTon20 [0] => Jfulton35 [2] => jfuLton100 ) 

Our third example would help us understand the behavior of array_multisort().

 <?php
 $array_name= array("James Fulton", "Karuna Simon", "Mark Simpson", "Amanda Moore");
 $array_id = array("Jfulton", "karuna001", "marksimpson", "amoore");
 $array_zip= array("10110", "30330", "20220", "50550");

 echo "Before array multisort, the arrays are: <br>";
 print_r($array_name); echo "<br>";
 print_r($array_id); echo "<br>";
 print_r($array_zip);

 array_multisort($array_name, $array_id, $array_zip);
 echo "<br><br> After array multisort, the arrays are: <br>";
 print_r($array_name); echo "<br>";
 print_r($array_id); echo "<br>";
 print_r($array_zip);
 ?>

The output shows that even though all the three arrays are sorted, the values (name, id, and zipcode) pertaining to an initial index remain aligned even after sorting -- e.g. the values corresponding to the user "Amanda Moore" remain aligned (initially, these values are at index 3 and after sorting they move to index 0). We should note that the array_multisort() sorts only the first array and then moves the elements of the other arrays so that they retain their old relative indexing with respect to the first array. We provide the output below.

 Before array multisort, the arrays are:
 Array ( [0] => James Fulton [1] => Karuna Simon  [2] => Mark Simpson [3] => Amanda Moore )
 Array ( [0] => Jfulton      [1] => karuna001    [2] => marksimpson  [3] => amoore )
 Array ( [0] => 10110        [1] => 30330        [2] => 20220        [3] => 50550 )

 After array multisort, the arrays are:
 Array ( [0] => Amanda Moore [1] => James Fulton [2] => Karuna Simon  [3] => Mark Simpson )
 Array ( [0] => amoore       [1] => Jfulton      [2] => karuna001    [3] => marksimpson )
 Array ( [0] => 50550        [1] => 10110        [2] => 30330        [3] => 20220 ) 

Sorting Associative Arrays

The second set discusses functions that sort associative arrays: asort(), arsort(), ksort(), krsort(), natsort(), and natcasesort(). These functions can do sorting based on either the values or the keys. These functions also do an in-place sorting.

 /* Functions to sort associative arrays */
 asort($passed_associative_array)
 arsort($passed_associative_array) 
 ksort($passed_associative_array)
 krsort($passed_associative_array)
 natsort($passed_associative_array) 
 natcasesort($passed_associative_array)

Let us begin with a brief description of these functions. asort() sorts an array based on values; arsort() is similar to asort() but sorts in the reverse order. ksort() sorts an array based on keys; krsort() is similar to ksort() but sorts in the reverse order.

If the values consist of both alphabets and numerals, then using natsort() is the correct approach; function natcasesort() is the case-insensitive variant of natsort(). We saw earlier that functions natsort() and natcasesort() also sort indexed arrays. Please note that for associative array, natsort() sorts values of the array instead of the keys.

The first program demonstrates the usage of asort(), arsort(), ksort(), and krsort().

 <?php
 $array_user = array('name' => "jwayne", 'zipcode' => 10110, 
                     'city' => "palo alto", 'city2' => "san jose");
 echo "Username array: <br>";
 print_r($array_user);

 /* Sort based on values */
 asort($array_user);
 echo "<br><br> After asort(), the array is: <br>";
 print_r($array_user);

 /* Reverse-sort based on values */
 arsort($array_user);
 echo "<br><br> After arsort(), the array is: <br>";
 print_r($array_user);

 /* Sort based on keys */
 ksort($array_user);
 echo "<br><br> After ksort(), the array is: <br>";
 print_r($array_user);

 /* Reverse-sort based on keys */
 krsort($array_user);
 echo "<br><br> After krsort(), the array is: <br>";
 print_r($array_user);

 /* Don't use sort() with associative array */
 sort($array_user);
 echo "<br><br> After sorting, the array is: <br>";
 print_r($array_user);
 ?>

The output (provided below) demonstrates usage of the above functions. Please note that calling sort() on an associative array makes the array an indexed array and replaces the key with array indexes! Therefore, we should avoid calling sort() for associative arrays.

 Username array:
 Array ( [name] => jwayne [zipcode] => 10110 [city] => palo alto [city2] => san jose )

 After asort(), the array is:
 Array ( [name] => jwayne [city] => palo alto [city2] => san jose [zipcode] => 10110 )

 After arsort(), the array is:
 Array ( [zipcode] => 10110 [city2] => san jose [city] => palo alto [name] => jwayne )

 After ksort(), the array is:
 Array ( [city] => palo alto [city2] => san jose [name] => jwayne [zipcode] => 10110 )

 After krsort(), the array is:
 Array ( [zipcode] => 10110 [name] => jwayne [city2] => san jose [city] => palo alto )

 After sorting, the array is:
 Array ( [0] => jwayne [1] => palo alto [2] => san jose [3] => 10110 )

The second example demonstrates the usage of natsort() and natcasesort().

 <?php

 /* Demonstrate the usage of natsort() */
 $array_userid = array('userid4' => "jwayne", 'userid10' => "jwayne20", 
                       'userid12' => "jwayne1000", 'userid30' => "jwayne19");
 echo "<br><br> The userid array is: <br>";
 print_r($array_userid);

 /* Calling asort() for alpha-numeric elements would not provide natural ordering */
 asort($array_userid);
 echo "<br><br> After asort(), the userid array is: <br>";
 print_r($array_userid);

 /* natsort() provides natural ordering */
 natsort($array_userid);
 echo "<br><br> After natural sorting, the userid array is: <br>";
 print_r($array_userid);
 ?>

The output shows that when an array has elements that consist of both alphabets and numerals, natsort() is the correct way to sort.

 The userid array is:
 Array ( [userid4] => jwayne [userid10] => jwayne20 [userid12] => jwayne1000 [userid30] => jwayne19 )

 After asort(0, the userid array is:
 Array ( [userid4] => jwayne [userid12] => jwayne1000 [userid30] => jwayne19 [userid10] => jwayne20 )

 After natural sorting, the userid array is:
 Array ( [userid4] => jwayne [userid30] => jwayne19 [userid10] => jwayne20 [userid12] => jwayne1000 ) 

Sorting via User-defined Functions

 usort($array_username, 'user_defined_comparison_func');
 uasort($array_username, 'user_defined_comparison_func');
 uksort($array_username, 'user_defined_comparison_func');

The third set of sorting-functions allows users to pass their own comparison functions. There are three user-based sorting functions: usort() to sort an indexed array, uasort() to sort an associative arrays by values, and uksort() to sort an associative array by keys.

Let us take a look at a simple program that demonstrates the usage of these functions.

 <?php
 function user_compare_func($var1, $var2) {
     if ($var1 == $var2) 
         return 0;
     return (($var1 > $var2) ? 1 : -1);
 }

 $indexed_array_user = array("J Fulton", "K Simon", "M Simpson", "A Moore");
 echo "The indexed_array_user is: <br>";
 print_r($indexed_array_user);

 usort($indexed_array_user, 'user_compare_func');
 echo "<br><br>After user-based sorting, the indexed_array_user is: <br>";
 print_r($indexed_array_user);

 $assoc_array_user = array('name' => "jwayne", 'zipcode' => 10110, 'city' => "palo alto", 
                           'city2' => "san jose");
 echo "<br><br>The assoc_array_user is: <br>";
 print_r($assoc_array_user);

 uasort($assoc_array_user, 'user_compare_func');
 echo "<br><br> After user-based value sorting, the assoc_array_user is: <br>";
 print_r($assoc_array_user);

 uksort($assoc_array_user, 'user_compare_func');
 echo "<br><br> After user-based key sorting, the assoc_array_user is: <br>";
 print_r($assoc_array_user);

 ?>

The output of this example is straightforward.

 The indexed_array_user is:
 Array ( [0] => J Fulton [1] => K Simon [2] => M Simpson [3] => A Moore )

 After user-based sorting, the indexed_array_user is:
 Array ( [0] => A Moore [1] => J Fulton [2] => K Simon [3] => M Simpson )

 The assoc_array_user is:
 Array ( [name] => jwayne [zipcode] => 10110 [city] => palo alto [city2] => san jose )

 After user-based value sorting, the assoc_array_user is:
 Array ( [name] => jwayne [city] => palo alto [city2] => san jose [zipcode] => 10110 )

 After user-based key sorting, the assoc_array_user is:
 Array ( [city] => palo alto [city2] => san jose [name] => jwayne [zipcode] => 10110 ) 




comments powered by Disqus