Operations on Arrays


There are a number of common operations we will perform on arraysincluding sorting, merging, and using other built-in functions provided by PHPwhich we will cover here. It is important to note that many of these operations take an array as a parameter and modify the contents of that array (as if they were called by reference). These built-in functions are exceptions to the rule, which says you must use & to pass the parameter by reference.

Sorting Arrays

Since PHP arrays only keep the data in the order in which they were added, there will be times when you will want to reorder it. For this you will use some of the various sorting functions provided. The most straightforward of these is the sort method, which modifies an array by sorting its contents:

 <?php   $randomNumbers = array(5, 3, 6, 4, 2, 1);   var_dump($randomNumbers);   echo "<br/>\n";   sort($randomNumbers);   var_dump($randomNumbers); ?> 

The previous code prints the following output (which we have formatted slightly):

 array(6) { [0]=> int(5) [1]=> int(3) [2]=> int(6)            [3]=> int(4) [4]=> int(2) [5]=> int(1) } array(6) { [0]=> int(1) [1]=> int(2) [2]=> int(3)            [3]=> int(4) [4]=> int(5) [5]=> int(6) } 

As you can see, the values are sorted, and any keys associated with those values are lost and reassigned. A variation on the sort method is the asort method, which performs the sort but maintains the keys with their sorted values. If we had instead called the asort method on the $randomNumbers array, the output would be

 array(6) { [0]=> int(5) [1]=> int(3) [2]=> int(6)            [3]=> int(4) [4]=> int(2) [5]=> int(1) } array(6) { [5]=> int(1) [4]=> int(2) [1]=> int(3)            [3]=> int(4) [0]=> int(5) [2]=> int(6) } 

In this case, the keys have maintained their association with their values, which are now sorted. (Recall that integer keys/indices do not imply location in the array.)

Sorting Strings

You can easily sort string values, too:

 <?php   $drinks = array("Coffee", "Café au Lait", "Mocha", "Espresso",                   "Americano", "Latte");   print_r($drinks);   sort($drinks);   print_r($drinks); ?> 

This produces the following output:

 Array ( [0] => Coffee [1] => Café au Lait [2] => Mocha         [3] => Espresso [4] => Americano [5] => Latte ) Array ( [0] => Americano [1] => Café au Lait [2] => Coffee         [3] => Espresso [4] => Latte [5] => Mocha ) 

Please note that when you are sorting strings, the sort method merely considers the 8-bit ASCII value of each character in the string. This has the disadvantage of considering "Z" as coming before "a" (since the ASCII code for "Z" is lower), and being largely unable to handle non-English text. We will visit multi-lingual web applications in greater detail in Chapter 6, "Strings and Characters of the World."

There is a slight improvement on the default string-sorting algorithm, which can help when you have numbers embedded within your strings (such as filenames). If you were to have the files

 "report1.pdf", "report5.pdf", "report10.pdf", and "report15.pdf" 

the default sorting algorithm will order them as follows:

 "report1.pdf", "report10.pdf", "report15.pdf", "report5.pdf" 

A more "natural-feeling" sort of numbers encountered on a string can be obtained by calling the natsort method or the natcasesort. The latter has the advantage of ignoring case when sorting array values. This would then give us more pleasing output:

 "report1.pdf", "report5.pdf", "report10.pdf", "report15.pdf" 

Sorting Mixed Types

The sort function behaves unpredictably when asked to sort a mixture of types, and it can produce unexpected results. For arrays of mixed types, you are better served by providing your own comparison function and using a custom sorting function.

Custom Sorting Functions

When you want to control the sorting of arrays yourself, you can use the usort (and uasort) functions. This lets you specify your own sorting function and have it do the actual work of comparing the values in the array. Using our array of motorcycles from before as an example, if we wanted to sort the bikes by price, we could write a function to look in to the child arrays and compare the prices. The user-defined function returns a 1, 0, or 1, depending on whether the first value is greater than, equal to, or less than the second value. Consider the following code:

 <?php   function compare_price($in_bike1, $in_bike2)   {     if ($in_bike1["price"] > $in_bike2["price"])     {       return 1;     }     else if ($in_bike1["price"] == $in_bike2["price"])     {       return 0;     }     else     {       return -1;     }   }   $bikes = array();   $bikes["Tourmeister"] = array("name" => "Grande Tour Meister",                                 "engine_cc" => 1100,                                 "price" =>12999);   $bikes["Slasher1000"] = array("name" => "Slasher XYZ 1000",                                 "engine_cc" => 998,                                 "price" => 11450);   $bikes["OffRoadster"] = array("name" => "Off-Roadster",                                 "engine_cc" => 550,                                 "price" => "4295");   uasort($bikes, "compare_price");   foreach ($bikes as $bike)   {     echo "Bike {$bike['name']} costs \${$bike['price']}<br/>\n";   } ?> 

When run, it produces the following output:

 Bike Off-Roadster costs $4295 Bike Slasher XYZ 1000 costs $11450 Bike Grande Tour Meister costs $12999 

Sorting in Reverse

If you want to sort the arrays in reverse order, there are versions of the sort and asort methods that do thisrsort and arsort. (There is no equivalent ursort since you can simply reverse the return values of your custom function to get the same effect.)

Sorting by Key

There are versions of the key-sorting functions that let you sort by key instead of valueksort, krsort, and uksort. Since sorting by key inherently preserves the key index/name, there is no kasort. These functions reorganize the arrays based on the sort of the keys and preserve any values associated with the keys.

Other Array Operations

There are other interesting functions that operate on arrays, including different ways to combine arrays or produce one array from two others. We will discuss some of them now.

array_merge

The array_merge function takes two arrays and returns a single array, with the contents of the second appended to the first. Keys are preserved for both arrays unless the second array has string keys with the same string as the first array; if that is the case, the values at these keys in the first array will be overwritten. Also, items in the second array with integer keys present in the first array will have a new key number assigned to them and be appended to the end of the array.

 <?php   $ar1 = array('name' => 'Zeke', 10, 100);   $ar2 = array('name' => 'Zimbu', 2, 3, 4);   $newar = array_merge($ar1, $ar2);   print_r($newar); ?> 

The output of this would be:

 Array (   [name] => Zimbu   [0] => 10   [1] => 100   [2] => 2   [3] => 3   [4] => 4 ) 

array_combine

This method takes two arraysone for keys and one for valuesand returns a new array, with the keys being the values from the first array and the values being those from the second. It will fail (and return FALSE) when the two arrays are not equal in size.

 <?php   $ar1 = array('name', 'age', 'height');   $ar2 = array('Bob', 23, '5\'8"');   $newary = array_combine($ar1, $ar2);   print_r($newary); ?> 

The output of this code would be

 Array (   [name] => Bob   [age] => 23   [height] => 5'8" ) 

array_intersect

This method takes two arrays and returns the set of values that are present in both. The keys are preserved. (However, if the same values have different keys, the key from the first array specified will be used.)

 <?php   $ar1 = array('name' => 'Zeke', 10, 100);   $ar2 = array('eeek' => 'Zeke', 2, 3, 4, 10);   $newar = array_intersect($ar1, $ar2);   print_r($newar); ?> 

Our output would be

 Array (   [name] => Zeke   [0] => 10 ) 

array_search

To find a value within the array, you can use the array_search method. This takes as arguments the value to find (referred to in PHP documentation as the needle) and the array in which to find it (referred to as the haystack). The function returns the array key at which it found the value or FALSE if the value is not found.

 <?php   $ar1 = array(1, 10, 100, 23, 44, 562, 354);   var_dump(array_search(100, $ar1));   var_dump($key2 = array_search(3333, $ar1)); ?> 

This snippet prints

 int(2) bool(false) 




Core Web Application Development With PHP And MYSQL
Core Web Application Development with PHP and MySQL
ISBN: 0131867164
EAN: 2147483647
Year: 2005
Pages: 255

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net