3.1 Arrays

Programmers continually have to deal with collections of data items. For instance, when you query a database for products, you may get a collection with multiple results. In PHP, as with many programming languages, you can handle these results through an array. An array can be considered a name that refers to many related items.

Arrays in PHP are sophisticated and more flexible than in many other high-level languages. A PHP array is an ordered set of variables, in which each variable?called an element? has an associated key . PHP allows elements to be accessed using either string or integer keys?PHP automatically assigns integer key values if keys are not specified when arrays are constructed.

Arrays can hold scalar values (integers, Booleans, strings, or floats) or compound values (objects and even other arrays). The same array can even hold elements of different types. In this section, we show how arrays are constructed and introduce several useful array functions from the PHP library.

3.1.1 Creating Arrays

PHP provides the array( ) language construct that creates arrays. The following examples show how arrays of integers and strings can be constructed and assigned to variables for later use:

$numbers = array(5, 4, 3, 2, 1);

$words = array("Web", "Database", "Applications");



// Print the third element from the array of integers: 3

print $numbers[2];



// Print the first element from the array of strings: "Web"

print $words[0];

By creating arrays this way, PHP assigns integer keys, or indexes to each element. By default, the index for the first element in an array is 0?this may seem odd but think of the index as an offset from the starting position in an array. The values contained in an array can be retrieved and modified using the bracket [ ] syntax. You can also create an array by assigning elements to a new, unset variable. The following code fragment illustrates the bracket syntax with an array of strings:

$newArray[0] = "Potatoes";

$newArray[1] = "Carrots";

$newArray[2] = "Spinach";



// Replace the third element

$newArray[2] = "Tomatoes";

In this example, PHP automatically treats $newArray as an array without a call to array( ).

An empty array can be created by assigning to a variable the return value of array( ). Values can then be added using the bracket syntax. PHP automatically assigns the next numeric index as the key (the largest integer key value plus one) when a key isn't supplied. The result of the following fragment is an array containing three items.

$shopping = array( );



$shopping[] = "Milk";

$shopping[] = "Coffee";

$shopping[] = "Sugar";

It's also easy to print individual element values themselves:

print $shopping[0];   // prints "Milk"

print $shopping[1];   // prints "Coffee"

print $shopping[2];   // prints "Sugar"

When printing array elements in double-quoted strings, you need to use the braces syntax introduced in Chapter 2, for example:

// prints "The first item in my list is Milk"

print "The first item in my list is {$shopping[0]}";

You can also print out the entire contents of an array using the print_r( ) function that we introduced in Chapter 2. Passing the variable $shopping from the previous example to print_r( ):

print_r($shopping);

prints the entire array showing each element and associated index:

Array

(

    [0] => Milk

    [1] => Coffee

    [2] => Sugar

)

To including print_r( ) output as part of a web page, you should use <pre> tags to preserve the formatting, otherwise the output is rendered on one line because one or more consecutive white space characters is treated as a single space in HTML. Generally you should avoid the use of the <pre> tag in your HTML output, however preserving the print_r( ) format makes debugging much easier. Here's how you can use the <pre> tags:

<pre>

<?php  print_r($shopping);  ?>

</pre>

While the print_r( ) function is really only intended for debugging purposes, and the use of <pre> elements in HTML is discouraged, we use the print_r( ) function extensively in this chapter to help illustrate our examples.

3.1.1.1 Associative arrays

An associative array uses string keys to access values stored in the array. An associative array can be constructed with array( ) by associating each key to a value using the => operator as shown in the following example:

$array = array("first"=>1, "second"=>2, "third"=>3);



// Print out the second element: prints "2"

print $array["second"];

The same array of integers can also be created with the bracket syntax:

$array["first"] = 1;

$array["second"] = 2;

$array["third"] = 3;

The => operator can also be used to create numerically indexed arrays that start at any index value. Often it's convenient to start an array at index 1, as shown in the following example:

$numbers = array(1=>"one", "two", "three", "four");

Arrays can also be created where each numeric key is specified, such as:

$oddNumbers = array(1=>"one", 3=>"three", 5=>"five");

All arrays in PHP are associative with elements accessed either by a string key or an integer key. You can create arrays that use both integer and string keys, however such arrays add complexity to an application and should be avoided. Associative arrays are common in other languages and are sometimes called hash arrays or hash tables?a reference to how the array is implemented.

3.1.1.2 Removing elements from an array

An element can be removed from an array, or an entire array can be deleted, by calling unset( ) . However, removing an element doesn't reassign the indexes as the following example shows:

$favorites = array("PHP", "Ace", "COBOL", "Java", "C++");



// remove COBOL from the array

unset($favorites[2]);

print_r($favorites);

Initially, each element is assigned a numeric key starting from zero, and after removing an element, the script prints:

Array ( [0] => PHP [1] => Ace [3] => Java [4] => C++ )

There is no longer an element defined for index 2. This example illustrates the associative nature of all PHP arrays: after a value is added to an array, the associated key remains unchanged unlike a true index that would adjust when an array changes.

To destroy a whole array, call unset( ) on the array variable:

// destroy the whole array

unset($favorites);

3.1.1.3 Array order

Arrays preserve the order of the elements that they contain, and new elements are appended to the end of an existing array. The following fragment creates an array specifying the integer indexes 1, 3, and 5; then adds values with the index values 2, 4, and 6.

$numbers = array(1=>"one", 3=>"three", 5=>"five");



$numbers[2] = "two";

$numbers[4] = "four";

$numbers[6] = "six";



print_r($numbers);

The resulting order is shown when the array contents are viewed with print_r( ):

Array

(

    [1] => one

    [3] => three

    [5] => five

    [2] => two

    [4] => four

    [6] => six

)

3.1.1.4 Heterogeneous arrays

The values that can be stored in a single PHP array don't have to be of the same type; PHP arrays can contain heterogeneous values?that is any mix of integer, string, Boolean, float, object, and even array variables. The following example shows the heterogeneous array $mixedBag:

$mixedBag = array("cat", 42, 8.5, false);



var_dump($mixedBag);

The function var_dump( ) displays the types and values of each element (with some whitespace added for clarity):

array(4) 

{

    [0] => string(3) "cat" 

    [1] => int(42) 

    [2] => float(8.5) 

    [3] => bool(false) 

}

3.1.1.5 Multidimensional arrays

Often data can't be represented in a simple array of scalar values?integers, strings, Booleans, and floats. Some data can only be represented when arrays hold other arrays of values. Consider representing the results from the twelve times table we showed in the previous chapter. We could create an array for each table from one to twelve:

$one = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);

$two = array(2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24);

$three = array(3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36);

// etc..

or we can create a multidimensional array like this:

$table = array(

    1 => array(1 => 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12),

    2 => array(1 => 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24),

    3 => array(1 => 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36),

... 

);

The variable $table is a two-dimensional array: each element?accessed by the integer 1, 2, 3, and so on?is an array that holds the results of a multiplication. Values can be accessed using [] operators for each dimension. We have explicitly set the index for the first element in each row, and for each row, allowed the terms used in a multiplication to be used as keys. For example, the following prints the result of 3 times 8:

// Prints 24

print $table[3][8];

Example 3-1 shows how more complex multidimensional arrays can be constructed.

Example 3-1. Examples of multidimensional arrays in PHP
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

                      "http://www.w3.org/TR/html401/loose.dtd">

<html>

<head>

  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

  <title>Multi-dimensional arrays</title>

</head>

<body bgcolor="#ffffff">

<h2>A two dimensional array</h2>

<?php



  // A two dimensional array using integer indexes

  $planets = array(array("Mercury", 0.39, 0.38),

                   array("Venus",   0.72, 0.95),

                   array("Earth",   1.0,  1.0),

                   array("Mars",    1.52, 0.53) );



  // prints "Earth"

  print $planets[2][0]

?>



<h2>More sophisticated multi-dimensional array</h2>

<?php



  // More sophisticated multi-dimensional array

  $planets2 = array(

    "Mercury"=> array("dist"=>0.39, "dia"=>0.38),

    "Venus"  => array("dist"=>0.72, "dia"=>0.95),

    "Earth"  => array("dist"=>1.0,  "dia"=>1.0,

                      "moons"=>array("Moon")),

    "Mars"   => array("dist"=>0.39, "dia"=>0.53,

                      "moons"=>array("Phobos", "Deimos"))

    );



  // prints "Moon"

  print $planets2["Earth"]["moons"][0];

?>

</body>

</html>

The first array constructed in Example 3-1 is two-dimensional and is accessed using integer indexes. The array $planets contains four elements, each of which is an array that contains three values: the planet's name, its distance from the Sun relative to the Earth's distance, and the planet's diameter relative to the Earth.

The second array in Example 3-1 is a little more sophisticated: the array $planets2 uses associative keys to identify an array that holds information about a planet. Each planet has an array of values that are associatively indexed by the name of the property that is stored. For those planets that have moons, an extra property is added that holds an array of the moon names.

To include an element from a multi-dimensional array in a double-quoted string, you need to use the braces syntax introduced in Chapter 2. When using braces, you don't need to escape the double-quotes that surround the array key; for example:

// prints "The Moon is a balloon"

print "The {$planets2["Earth"]["moons"][0]} is a balloon";

Many data structures (such as property lists, stacks, queues, and trees) can be created using PHP arrays. We limit our usage of arrays to simple structures; the examination of more complex data structures is outside the scope of this book.

3.1.2 Using foreach Loops with Arrays

The easiest way to traverse or iterate through an array is using the foreach statement. The foreach statement has two forms:

foreach(array_expression as $value)

{

    // body of loop

}



foreach(array_expression as $key => $value)

{

    // body of loop

}

Both step through an array expression, executing the statements contained in the body of the loop for each element in the array. The first form assigns the value from the element to a variable identified with the as keyword. The second form assigns both the key and the value to a pair of variables. Variables assigned with an element value and key, are available in the body of the loop.

The following example shows the first form in which the array expression is the variable $lengths, and each value is assigned to the variable $cm:

// Construct an array of integers

$lengths = array(0, 107, 202, 400, 475);



// Convert an array of centimeter lengths to inches

foreach($lengths as $cm)

{

    $inch = $cm / 2.54;

    print "{$cm} centimeters = {$inch} inches\n";

}

The example iterates through the array in the same order it was created:

0 centimeters = 0 inches 

107 centimeters = 42.125984251969 inches

202 centimeters = 79.527559055118 inches

400 centimeters = 157.48031496063 inches

475 centimeters = 193.87755102041 inches

The first form of the foreach statement iterates through the values of an associative array, but keys are not retrieved. The second form assigns both the key and the value to variables identified as $key => $value. The next example shows how the key is assigned to $animal, and the value is assigned to $sound to generate verses of "Old MacDonald":

// Old MacDonald

$sounds = array("cow"=>"moo", "dog"=>"woof", 

                "pig"=>"oink", "duck"=>"quack");



foreach ($sounds as $animal => $sound)

{

    print "<p>Old MacDonald had a farm EIEIO";

    print "<br>And on that farm he had a {$animal} EIEIO";

    print "<br>With a {$sound}-{$sound} here"; 

    print "<br>And a {$sound}-{$sound} there"; 

    print "<br>Here a {$sound}, there a {$sound}"; 

    print "<br>Everywhere a {$sound}-{$sound}"; 

    print "<p>Old MacDonald had a farm EIEIO";

}

This prints a verse for each $animal/$sound pair in the $sounds array; here are the first two verses:

Old MacDonald had a farm EIEIO

And on that farm he had a cow EIEIO

With a moo-moo here

And a moo-moo there

Here a moo, there a moo

Everywhere a moo-moo

Old MacDonald had a farm EIEIO



Old MacDonald had a farm EIEIO

And on that farm he had a dog EIEIO

With a woof-woof here

And a woof-woof there

Here a woof, there a woof

Everywhere a woof-woof

Old MacDonald had a farm EIEIO

When the second form of the foreach statement is used with an array with integer keys, the key is assigned the integer index.

3.1.3 Basic Array Functions

In this section, we introduce selected basic PHP array library functions.

3.1.3.1 Counting elements in arrays

The count( ) function returns the number of elements in the array var:

integer count(mixed var)

Using it, the following example prints 7:

$days = array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun");



print count($days);  // 7

The count( ) function works on any variable type and returns 0 when either an empty array or an unset variable is examined. If you want to be sure that count( ) is called on an array variable, the is_array( ) function should be called first.

The array_count_values( ) function counts the instances of each value in an input array, returning a new associative array of the resultant counts:

array array_count_values(array input)

The following example illustrates how the function works:

$pets = array("Beth"=>"Dog", "Arabella"=>"Rabbit", "Meg"=>"Cat",

              "Louise"=>"Chicken", "Ben"=>"Dog", "Neda"=>"Cat");



$petFrequency = array_count_values($pets);



// prints 2

print $petFrequency["Dog"];



// prints:

// Array ( [Dog] => 2 [Rabbit] => 1 [Cat] => 2 [Chicken] => 1 )

print_r($petFrequency);

3.1.3.2 Functions that create arrays

PHP provides two functions that create new arrays with pre-filled values:

array array_fill(integer start, integer count, mixed value)
array range(mixed low, mixed high [, integer step])

The function array_fill( ) returns a new array of count elements, their keys starting at index start, all set to the same value. The function range( ) returns a new array filled with a sequence of elements starting with the value low to the value high. The optional step value?introduced in PHP 5?determines the increments between elements in the new array. The following examples show how these two functions work:

// Sets $unity to:

//   Array ( [2] => one [3] => one [4] => one [5] => one [6] => one )

$unity = array_fill(2, 5, "one");



// sets $teens to:

//   Array ( [0] => 13 [1] => 14 [2] => 15 [3] => 16 

//           [4] => 17 [5] => 18 [6] => 19 )

$teens = range(13, 19);



// sets $letters to:

//   Array ( [0] => A [1] => B [2] => C [3] => D [4] => E [5] => F )

$letters = range("A", "F");



// This only works in PHP5

// sets $oddNumbers to 

//   Array ( [0] => 1 [1] => 3 [2] => 5 [3] => 7 [4] => 9 )

$oddNumbers = range(1, 10, 2);



// This only works in PHP5

// sets $fifthLetters to

//    Array ( [0] => a [1] => f [2] => k [3] => p [4] => u [5] => z )

$fifthLetters = range("a", "z", 5);

3.1.3.3 Exploding and imploding strings

PHP provides the explode( ) , implode( ), and join( ) functions, which convert strings to arrays and back to strings:

array explode(string separator, string subject [, integer limit])
string implode(string glue, array pieces)
string join(string glue, array pieces)

The explode( ) function returns an array of strings created by breaking the subject string at each occurrence of the separator string. The optional integer limit determines the maximum number of elements in the resulting array; when the limit is met, the last element in the array is the remaining unbroken subject string. The implode( ) function returns a string created by joining each element in the array pieces, inserting the string glue between each piece. join( ) is an alias to implode( ) and operates exactly the same way. The following example shows both the implode( ) and explode( ) functions:

$words = explode(" ", "Now is the time");



// Prints: Array ( [0] => Now [1] => is [2] => the [3] => time )

print_r($words);



$animalsSeen = array("kangaroo", "wombat", "dingo", "echidna");



// prints:

// Animals I've seen: kangaroo, wombat, dingo, echidna

print "Animals I've seen: " . implode(", ", $animalsSeen);

In the example, explode( ) creates a new array by breaking the phrase "Now is the time" at each space. The resulting elements do not incorporate the separating spaces?they get thrown away. The implode( ) function turns the array into a string; the glue results in a comma-separated animal names. It is common to use the implode( ) function when you want to print the contents of an array in a message.

Later in Section 3.3 we describe the functions split( ) and spliti( ) as alternatives to the explode( ). While these functions use regular expressions to define the separator and allow more complex behavior, the explode( ) function is more efficient and should be used for simple tasks.

3.1.3.4 Finding the maximum and minimum values in an array

The maximum and minimum values can be found from an array numbers with max( ) and min( ) , respectively:

number max(array numbers)
number min(array numbers)

If an array of integers is examined, the returned result is an integer as in the following example:

$var = array(10, 5, 37, 42, 1, -56);

print max($var);  // prints 42

print min($var);  // prints -56

If an array of floats is examined, min( ) and max( ) return a float.

Both min( ) and max( ) can also be called with a list of integer or float arguments:

number max(number arg1, number arg2, number arg3, ...)
number min(number arg1, number arg2, number arg3, ...)

In this case, they return the maximum or minimum value in the list. Neither max( ) or min( ) complain when they're passed strings or arrays of strings, but the results may not always be as expected and the string functions we discuss later should be used instead.

3.1.3.5 Finding values in arrays with in_array( ) and array_search( )

The in_array( ) function returns true if an array haystack contains a specific value needle:

boolean in_array(mixed needle, array haystack [, boolean strict])

The following example searches the array of integers $smallPrimes for the integer 19:

$smallPrimes = array(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);



$var = 19;



if (in_array($var, $smallPrimes)) 

    print "{$var} is a small prime number"; // Always printed

A third, optional argument can be passed that enforces a strict type check when comparing each element with the needle. In the following example, in_array( ) with two parameters would return true as automatic type conversion turns the string into an integer. However, with strict type checking, the string "19 Bridge Rd, Richmond" doesn't match the integer 19 held in the array and so the function returns false:

$smallPrimes = array(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);



$var = "19 Bridge Rd, Richmond";



// Strict type checking -- message not printed

if (in_array($var, $smallPrimes, true))

    print "{$var} is a small prime number";



// No type checking -- message is printed

if (in_array($var, $smallPrimes))

    print "{$var} is a small prime number";

The array_search( ) function (introduced with PHP 4.0.5) works the same way as the in_array( ) function, except the key of the matching value needle is returned rather than the Boolean value true:

mixed array_search(mixed needle, array haystack [, boolean strict])

The following fragment shows how array_search( ) works:

$measure = array("inch"=>1, "foot"=>12, "yard"=>36);



// prints "foot"

print array_search(12, $measure);



$units = array("inch", "centimeter", "chain", "furlong");



// prints 2

print array_search("chain", $units);

If the value isn't found, array_search( ) returns false. The third, optional parameter strict directs array_search( ) to compare both value and type when searching for a match.

A problem can exist when the first element is found, because the return value is 0 and is hard to distinguish from false.

Care must be taken with functions, such as array_search( ), that return a result on success, or the Boolean value false to indicate when a result can't be determined. If the return value is used as a Boolean?in an expression or as a Boolean parameter to a function?a valid result may be automatically converted to false. If such a function returns 0, 0.0, an empty string, or an empty array, PHP's automatic type conversion converts the result to false when a Boolean value is required.


The correct way to test the result of functions that return mixed values is to use the is-identical operator ===, as shown in the following example:

$units = array("inch", "centimeter", "chain", "furlong");



$index = array_search("inch", $units);



if ($index === false)

    print "Unknown unit: inch";

else

    // OK to use $index

    print "Index = {$index}"; // Prints Index = 0

3.1.3.6 Keys and values

You can check the existence of an element before using it with the array_key_exists( ) function. If there is an element in the source array associated with the key, then the function returns true:

boolean array_key_exists(mixed key, array source)

The following example searches the array $pets for a particular $owner and either prints the corresponding pet $pets[$owner], or reports that the $owner was not found as a key in the source array:

$pets = array("Beth"=>"Dog", "Arabella"=>"Rabbit", "Meg"=>"Cat",

              "Louise"=>"Chicken", "Ben"=>"Dog", "Neda"=>"Cat");



$owner = "Eddie";



if (array_key_exists($owner, $pets))

    print "{$owner} has a {$pets[$owner]} as a pet";

else

{

    print "{$owner} doesn't have a pet.\n";

    print "Pet owners are: " . implode(array_keys($pets), ", ");

}

A list of known pet owners is printed by calling the array_keys( ) function and gluing the result together using the implode( ) function discussed earlier in the chapter. The preceding example prints the message:

Eddie doesn't have a pet. 

Pet owners are: Beth, Arabella, Meg, Louise, Ben, Neda

The array_keys( ) function can also be used to find the keys for a particular value:

array array_keys(array input [, mixed search_value])

When the function is called with an optional search_value, only keys associated with that value are returned:

$pets = array("Beth"=>"Dog", "Arabella"=>"Rabbit", "Meg"=>"Cat",

              "Louise"=>"Chicken", "Ben"=>"Dog", "Neda"=>"Cat");



$dogOwners = array_keys($pets, "Dog");



// Prints: Array ( [0] => Beth [1] => Ben )

print_r($dogOwners);

Sometimes it's useful to consider the values of an associative array without the keys. PHP provides the array_values( ) function that creates a new array with the values from the input array and adds a numeric index:

array array_values(array input)

For example, the $pets array in the following fragment is transformed into a numerically-indexed list of pet types:

$pets = array("Beth"=>"Dog", "Arabella"=>"Rabbit", "Meg"=>"Cat",

              "Louise"=>"Chicken", "Ben"=>"Dog", "Neda"=>"Cat");



// Array ( [0] => Dog [1] => Rabbit [2] => Cat [3] => Chicken 

//         [4] => Dog [5] => Cat )

$petTypes = array_values($pets);

The following fragment generates a list of unique values from the array $pets by passing the array returned by array_values( ) directly into the function array_unique( ). The implode( ) function is called to create a simple message:

$pets = array("Beth"=>"Dog", "Arabella"=>"Rabbit", "Meg"=>"Cat",

              "Louise"=>"Chicken", "Ben"=>"Dog", "Neda"=>"Cat");



$uniquePetTypes = array_unique(array_values($pets));



// Prints 

// Pets seen : Dog, Rabbit, Cat, Chicken

print "Pets seen : " . implode(", ", $uniquePetTypes);

3.1.3.7 Joining two or more arrays

Arrays can be merged using the + operator. However, values with the same index or key are overwritten. In contrast, the array_merge( ) function provides a method of appending two or more arrays together without overwriting values:

array array_merge( array array1, array array2 [, array ...])

The behavior of both the + operator and the array_merge( ) function is illustrated in this example:

$clothing = array("silk", "satin", "cotton", "rags");

$dwelling = array("house", "tree", "palace");

$cointoss = array("heads", "tails");



$added = $cointoss + $dwelling + $clothing;



// prints: 

// Array ( [0] => heads [1] => tails [2] => palace [3] => rags ) 

print_r($added);



$merged = array_merge($cointoss, $dwelling, $clothing);



// prints: 

// Array ( [0] => heads [1] => tails [2] => house [3] => tree 

//         [4] => palace [5] => silk [6] => satin [7] => cotton 

//         [8] => rags ) 

print_r($merged);

The result of the array addition in the previous example deserves some explanation:

$added = $cointoss + $dwelling + $clothing;

PHP calculates the addition from right to left: first the $clothing array is overwritten by the $dwelling array, then the result of that addition is overwritten by the $cointoss array.

3.1.3.8 Reordering elements with array_reverse( )

The array_reverse( ) function returns a new array by reversing the elements from a source array:

array array_reverse(array source [, bool preserve_keys])

The following example shows how to reverse an indexed array of strings:

$count = array("zero", "one", "two", "three", "four");

$countdown = array_reverse($count);

Setting the optional preserve_keys argument to true reverses the order but preserves the association between the index and the elements. For a numerically indexed array, this means that the order of the elements is reversed, but the indexes that access the elements don't change. The following example shows what happens:

$count = array("zero", "one", "two", "three", "four");

$countdown = array_reverse($count, true);

print_r($countdown);

This prints:

Array ( [4] => four [3] => three [2] => two [1] => one [0] => zero )

3.1.4 Sorting Arrays

In this section, we show you how to sort arrays. Unlike the array_reverse( ) function discussed in the previous section (which returns a copy of the source array), the sorting functions rearrange the elements of the source array itself?the source array parameter is passed as a reference, not a value. Because of this behavior, the sort functions must be passed a variable and not an expression.

3.1.4.1 Sorting with sort( ) and rsort( )

The simplest array-sorting functions are sort( ) and rsort( ), which rearrange the elements of the subject array in ascending and descending order, respectively:

sort(array subject [, integer sort_flag])
rsort(array subject [, integer sort_flag])

Both functions sort the subject array based on the values of each element. The following example shows the sort( ) function applied to an array of integers:

$numbers = array(24, 19, 3, 16, 56, 8, 171);

sort($numbers);



foreach($numbers as $n)

    print $n ." ";

The output of the example prints the elements sorted by value:

3 8 16 19 24 56 171

The result of the sort( ) function is further illustrated with the output of print_r($numbers):

Array 

( 

    [0] => 3 

    [1] => 8 

    [2] => 16 

    [3] => 19 

    [4] => 24 

    [5] => 56 

    [6] => 171 

)

The following example shows the rsort( ) function on the same array:

$numbers = array(24, 19, 3, 16, 56, 8, 171);

rsort($numbers);

print_r($numbers);

The output of the example shows the elements sorted in reverse order by value:

Array 

( 

    [0] => 171 

    [1] => 56 

    [2] => 24 

    [3] => 19 

    [4] => 16 

    [5] => 8 

    [6] => 3 

)

By default, PHP sorts strings in alphabetical order and numeric values in numeric order. An optional parameter, sort_flag, can be passed to force either string or numeric sorting behavior. In the following example, the PHP constant SORT_STRING sorts the numbers as if they were strings:

$numbers = array(24, 19, 3, 16, 56, 8, 171);

sort($numbers, SORT_STRING);

print_r($numbers);

The output of the example shows the result:

Array 

( 

    [0] => 16 

    [1] => 171 

    [2] => 19 

    [3] => 24 

    [4] => 3 

    [5] => 56 

    [6] => 8 

)

Many of the array sorting functions accept a sort_flag parameter. Other sort flags are SORT_REGULAR to compare items using the default approach and SORT_NUMERIC that forces items to be compared numerically. When an array that contains both strings and numeric values is sorted with the SORT_REGULAR flag, string values are sorted alphabetically and appear first, and numeric values are sorted numerically. Consider the result of sorting the following array $mixed:

$mixed= array(24, "dog", 19, 3, 56, 8, 171, "Bruce", "cat", "Nemo");



sort($mixed, SORT_REGULAR);

print_r($mixed);

The sorted elements in the $mixed array are printed with print_r( ):

Array

(

    [0] => Bruce

    [1] => Nemo

    [2] => cat

    [3] => dog

    [4] => 3

    [5] => 8

    [6] => 19

    [7] => 24

    [8] => 56

    [9] => 171

)

sort( ) and rsort( ) can be used on associative arrays, but the keys are lost. The resulting array contains only the values in the sorted order. Consider the following example:

$map =  array("o"=>"kk", "e"=>"zz", "z"=>"hh", "a"=>"rr");



sort($map);

print_r($map);

The print_r( ) output shows the modified array without the key values:

Array 

(

    [0] => hh 

    [1] => kk 

    [2] => rr 

    [3] => zz 





)

3.1.4.2 Sorting associative arrays

It's often desirable to keep the key/value associations when sorting associative arrays. To maintain the key/value association the asort( ) and arsort( ) functions are used:

asort(array subject [, integer sort_flag])
arsort(array subject [, integer sort_flag])

Like sort( ) and rsort( ), these functions rearrange the elements in the subject array from lowest to highest and highest to lowest, respectively. The sort order reflects the element values in the array, not the keys. The following example shows a simple array sorted by asort( ):

$map = array("o"=>"kk", "e"=>"zz", "z"=>"hh", "a"=>"rr");



asort($map);

print_r($map);

The print_r( ) function outputs the structure of the sorted array:

Array 

( 

    [z] => hh 

    [o] => kk 

    [a] => rr 

    [e] => zz 

)

When asort( ) and arsort( ) are used on non-associative arrays, the order of the elements is arranged in sorted order, but the indexes that access the elements don't change. The indexes are treated as association keys in the resulting array. The following example shows what is happening:

$numbers = array(24, 19, 3, 16, 56, 8, 171);

asort($numbers);

print_r($numbers);

This outputs:

Array 

( 

    [2] => 3 

    [5] => 8 

    [3] => 16 

    [1] => 19 

    [0] => 24 

    [4] => 56 

    [6] => 171

)

3.1.4.3 Sorting on keys

Rather than sort on element values, the ksort( ) and krsort( ) functions rearrange elements in an array by sorting on the keys or the indexes:

integer ksort(array subject [, integer sort_flag])
integer krsort(array subject [, integer sort_flag])

ksort( ) sorts the elements in the subject array from lowest key to highest key, and krsort( ) sorts in the reverse order. The following example demonstrates the ksort( ) function:

$map = array("o"=>"kk", "e"=>"zz", "z"=>"hh", "a"=>"rr");



ksort($map);

print_r($map);

The sorted array $map is now:

Array 

( 

    [a] => rr 

    [e] => zz 

    [o] => kk 

    [z] => hh 

)

3.1.4.4 Sorting with user-defined element comparison

The sorting functions described so far in this section sort elements in alphabetic or numeric order. To sort elements based on user-defined criteria, PHP provides three functions:

usort(array subject, string compare_function)
uasort(array subject, string compare_function)
uksort(array subject, string compare_function)

usort( ) sorts the subject array based on the value of each element and applies a new, numeric index, uasort( ) preserves the key/value associations as described earlier for the asort( ) function, and uksort( ) rearranges the elements based on the key of each element. When these functions sort the subject array, the user-defined compare function is called to determine if one element is greater than, lesser than, or equal to another. The compare function can be written to implement any sort order, but the function must conform to the prototype:

integer my_compare_function(mixed a, mixed b)

We discuss how to write functions in Chapter 2. Your compare function must take two parameters, a and b, and return a negative number if a is less than b, a positive number if a is greater than b, and 0 if a and b are equal. The method that the function uses to determine that one value is less than, greater than, or equal to another depends on the requirements of the sorting. The following example shows how usort( ) sorts an array of strings based on the length of each string:

// Compare two string values based on the length

function cmp_length($a, $b) 

{   

    if (strlen($a) < strlen($b)) 

        return -1;



    if (strlen($a) > strlen($b)) 

        return 1;



    // If we've reached this point, 

    // string lengths must be equal

    return 0;

}





$animals = array("cow", "ox", "hippopotamus", "platypus");



usort($animals, "cmp_length");



print_r($animals);

The array $animals is printed:

Array 

(

    [0] => ox 

    [1] => cow 

    [2] => platypus 

    [3] => hippopotamus

)

In this example, cmp_length( ) is defined as the compare function, but it isn't called directly by the script. The name of the function, "cmp_length", is passed as an argument to usort( ), and usort( ) uses cmp_length( ) as part of the sorting algorithm. User-defined functions used in this way are referred to as callback functions .