Wednesday, February 4, 2009

Arrays

As we discussed in Chapter 2, PHP supports both scalar and compound data types. In this chapter, we'll discuss one of the compound types: arrays. An array is a collection of data values, organized as an ordered collection of key-value pairs.

This chapter talks about creating an array, adding and removing elements from an array, and looping over the contents of an array. There are many built-in functions that work with arrays in PHP, because arrays are very common and useful. For example, if you want to send email to more than one email address, you'll store the email addresses in an array and then loop through the array, sending the message to the current email address. Also, if you have a form that permits multiple selections, the items the user selected are returned in an array.

Indexed Versus Associative Arrays

There are two kinds of arrays in PHP: indexed and associative. The keys of an indexed array are integers, beginning at 0. Indexed arrays are used when you identify things by their position. Associative arrays have strings as keys and behave more like two-column tables. The first column is the key, which is used to access the value.

PHP internally stores all arrays as associative arrays, so the only difference between associative and indexed arrays is what the keys happen to be. Some array features are provided mainly for use with indexed arrays, because they assume that you have or want keys that are consecutive integers beginning at 0. In both cases, the keys are unique--that is, you can't have two elements with the same key, regardless of whether the key is a string or an integer.

PHP arrays have an internal order to their elements that is independent of the keys and values, and there are functions that you can use to traverse the arrays based on this internal order. The order is normally that in which values were inserted into the array, but the sorting functions described later let you change the order to one based on keys, values, or anything else you choose.

Identifying Elements of an Array

You can access specific values from an array using the array variable's name, followed by the element's key (sometimes called the index) within square brackets:

$age['Fred']
$shows[2]

The key can be either a string or an integer. String values that are equivalent to integer numbers (without leading zeros) are treated as integers. Thus, $array[3] and $array['3'] reference the same element, but $array['03'] references a different element. Negative numbers are valid keys, and they don't specify positions from the end of the array as they do in Perl.

You don't have to quote single-word strings. For instance, $age['Fred'] is the same as $age[Fred]. However, it's considered good PHP style to always use quotes, because quoteless keys are indistinguishable from constants. When you use a constant as an unquoted index, PHP uses the value of the constant as the index:

define('index',5);
echo $array[index]; // retrieves $array[5], not $array['index'];

You must use quotes if you're using interpolation to build the array index:

$age["Clone$number"]

However, don't quote the key if you're interpolating an array lookup:

// these are wrong
print "Hello, $person['name']";
print "Hello, $person["name"]";
// this is right
print "Hello, $person[name]";

Storing Data in Arrays

Storing a value in an array will create the array if it didn't already exist, but trying to retrieve a value from an array that hasn't been defined yet won't create the array. For example:

// $addresses not defined before this point
echo $addresses[0]; // prints nothing
echo $addresses; // prints nothing
$addresses[0] = 'spam@cyberpromo.net';
echo $addresses; // prints "Array"

Using simple assignment to initialize an array in your program leads to code like this:

$addresses[0] = 'spam@cyberpromo.net';
$addresses[1] = 'abuse@example.com';
$addresses[2] = 'root@example.com';
// ...

That's an indexed array, with integer indexes beginning at 0. Here's an associative array:

$price['Gasket'] = 15.29;
$price['Wheel'] = 75.25;
$price['Tire'] = 50.00;
// ...

An easier way to initialize an array is to use the array( ) construct, which builds an array from its arguments:

$addresses = array('spam@cyberpromo.net', 'abuse@example.com',
'root@example.com');

To create an associative array with array( ), use the => symbol to separate indexes from values:

$price = array('Gasket' => 15.29,
'Wheel' => 75.25,
'Tire' => 50.00);

Notice the use of whitespace and alignment. We could have bunched up the code, but it wouldn't have been as easy to read:

$price = array('Gasket'=>15.29,'Wheel'=>75.25,'Tire'=>50.00);

To construct an empty array, pass no arguments to array( ):

$addresses = array( );

You can specify an initial key with => and then a list of values. The values are inserted into the array starting with that key, with subsequent values having sequential keys:

$days = array(1 => 'Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday', 'Saturday', 'Sunday');
// 2 is Tuesday, 3 is Wednesday, etc.

If the initial index is a non-numeric string, subsequent indexes are integers beginning at 0. Thus, the following code is probably a mistake:

$whoops = array('Friday' => 'Black', 'Brown', 'Green');
// same as
$whoops = array('Friday' => 'Black', 0 => 'Brown', 1 => 'Green');

Adding Values to the End of an Array

To insert more values into the end of an existing indexed array, use the [] syntax:

$family = array('Fred', 'Wilma');
$family[] = 'Pebbles'; // $family[2] is 'Pebbles'

This construct assumes the array's indexes are numbers and assigns elements into the next available numeric index, starting from 0. Attempting to append to an associative array is almost always a programmer mistake, but PHP will give the new elements numeric indexes without issuing a warning:

$person = array('name' => 'Fred');
$person[] = 'Wilma'; // $person[0] is now 'Wilma'

Assigning a Range of Values

The range( ) function creates an array of consecutive integer or character values between the two values you pass to it as arguments. For example:

$numbers = range(2, 5); // $numbers = array(2, 3, 4, 5);
$letters = range('a', 'z'); // $numbers holds the alphabet
$reversed_numbers = range(5, 2); // $numbers = array(5, 4, 3, 2);

Only the first letter of a string argument is used to build the range:

range('aaa', 'zzz') /// same as range('a','z')

Getting the Size of an Array

The count( ) and sizeof( ) functions are identical in use and effect. They return the number of elements in the array. There is no stylistic preference about which function you use. Here's an example:

$family = array('Fred', 'Wilma', 'Pebbles');
$size = count($family); // $size is 3

These functions do not consult any numeric indexes that might be present:

$confusion = array( 10 => 'ten', 11 => 'eleven', 12 => 'twelve');
$size = count($confusion); // $size is 3

Padding an Array

To create an array initialized to the same value, use array_pad( ). The first argument to array_pad( ) is the array, the second argument is the minimum number of elements you want the array to have, and the third argument is the value to give any elements that are created. The array_pad( ) function returns a new padded array, leaving its argument array alone.

Here's array_pad( ) in action:

$scores = array(5, 10);
$padded = array_pad($scores, 5, 0); // $padded is now array(5, 10, 0, 0, 0)

Notice how the new values are appended to the end of the array. If you want the new values added to the start of the array, use a negative second argument:

$padded = array_pad($scores, -5, 0);

Assign the results of array_pad( ) back to the original array to get the effect of an in situ change:

$scores = array_pad($scores, 5, 0);

If you pad an associative array, existing keys will be preserved. New elements will have numeric keys starting at 0.
Multidimensional Arrays

The values in an array can themselves be arrays. This lets you easily create

multidimensional arrays:

$row_0 = array(1, 2, 3);
$row_1 = array(4, 5, 6);
$row_2 = array(7, 8, 9);
$multi = array($row_0, $row_1, $row_2);

You can refer to elements of multidimensional arrays by appending more []s:

$value = $multi[2][0]; // row 2, column 0. $value = 7

To interpolate a lookup of a multidimensional array, you must enclose the entire array lookup in curly braces:

echo("The value at row 2, column 0 is {$multi[2][0]}\n");

Failing to use the curly braces results in output like this:

The value at row 2, column 0 is Array[0]

Extracting Multiple Values

To copy all of an array's values into variables, use the list( ) construct:

list($variable, ...) = $array;

The array's values are copied into the listed variables, in the array's internal order. By default that's the order in which they were inserted, but the sort functions described later let you change that. Here's an example:

$person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Betty');
list($n, $a, $w) = $person; // $n is 'Fred', $a is 35, $w is 'Betty'

If you have more values in the array than in the list( ), the extra values are ignored:

$person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Betty');
list($n, $a) = $person; // $n is 'Fred', $a is 35

If you have more values in the list( ) than in the array, the extra values are set to NULL:

$values = array('hello', 'world');
list($a, $b, $c) = $values; // $a is 'hello', $b is 'world', $c is NULL

Two or more consecutive commas in the list( ) skip values in the array:

$values = range('a', 'e');
list($m,,$n,,$o) = $values; // $m is 'a', $n is 'c', $o is 'e'

Slicing an Array

To extract only a subset of the array, use the array_slice( ) function:

$subset = array_slice(array, offset, length);

The array_slice( ) function returns a new array consisting of a consecutive series of values from the original array. The offset parameter identifies the initial element to copy (0 represents the first element in the array), and the length parameter identifies the number of values to copy. The new array has consecutive numeric keys starting at 0. For example:

$people = array('Tom', 'Dick', 'Harriet', 'Brenda', 'Jo');
$middle = array_slice($people, 2, 2); // $middle is array('Harriet', 'Brenda')

It is generally only meaningful to use array_slice( ) on indexed arrays (i.e., those with consecutive integer indexes, starting at 0):

// this use of array_slice( ) makes no sense
$person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Betty');
$subset = array_slice($person, 1, 2); // $subset is array(0 => 35, 1 => 'Betty')

Combine array_slice( ) with list( ) to extract only some values to variables:

$order = array('Tom', 'Dick', 'Harriet', 'Brenda', 'Jo');
list($second, $third) = array_slice($order, 1, 2);
// $second is 'Dick', $third is 'Harriet'

Splitting an Array into Chunks

To divide an array into smaller, evenly sized arrays, use the array_chunk( ) function:

$chunks = array_chunk(array, size [, preserve_keys]);

The function returns an array of the smaller arrays. The third argument, preserve_keys, is a Boolean value that determines whether the elements of the new arrays have the same keys as in the original (useful for associative arrays) or new numeric keys starting from 0 (useful for indexed arrays). The default is to assign new keys, as shown here:

$nums = range(1, 7);
$rows = array_chunk($nums, 3);
print_r($rows);
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[0] => 4
[1] => 5
[2] => 6
)
[2] => Array
(
[0] => 7
)
)

Keys and Values

The array_keys( ) function returns an array consisting of only the keys in the array, in internal order:

$array_of_keys = array_keys(array);

Here's an example:

$person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Wilma');
$keys = array_keys($person); // $keys is array('name', 'age', 'wife')

PHP also provides a (less generally useful) function to retrieve an array of just the values in an array, array_values( ):

$array_of_values = array_values(array);

As with array_keys( ), the values are returned in the array's internal order:

$values = array_values($person); // $values is array('Fred', 35, 'Wilma');

Checking Whether an Element Exists

To see if an element exists in the array, use the array_key_exists( ) function:

if (array_key_exists(key, array)) { ... }

The function returns a Boolean value that indicates whether the second argument is a valid key in the array given as the first argument.

It's not sufficient to simply say:

if ($person['name']) { ... } // this can be misleading

Even if there is an element in the array with the key name, its corresponding value might be false (i.e., 0, NULL, or the empty string). Instead, use array_key_exists( ) as follows:

$person['age'] = 0; // unborn?
if ($person['age']) {
echo "true!\n";
}
if (array_key_exists('age', $person)) {
echo "exists!\n";
}
exists!

In PHP 4.0.6 and earlier versions, the array_key_exists( ) function was called key_exists( ). The original name is still retained as an alias for the new name.

Many people use the isset( ) function instead, which returns true if the element exists and is not NULL:

$a = array(0,NULL,'');
function tf($v) { return $v ? "T" : "F"; }
for ($i=0; $i < removed =" array_splice(array," subjects =" array('physics'," removed =" array_splice($subjects," removed =" array_splice($subjects," new =" array('law'," new =" array('law'," subjects =" array('physics'," new =" array('law'," capitals =" array('USA'"> 'Washington',
'Great Britain' => 'London',
'New Zealand' => 'Wellington',
'Australia' => 'Canberra',
'Italy' => 'Rome');
$down_under = array_splice($capitals, 2, 2); // remove New Zealand and Australia
$france = array('France' => 'Paris');
array_splice($capitals, 1, 0, $france); // insert France between USA and G.B.

Converting Between Arrays and Variables

PHP provides two functions, extract( ) and compact( ), that convert between arrays and variables. The names of the variables correspond to keys in the array, and the values of the variables become the values in the array. For instance, this array:

$person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Betty');

can be converted to, or built from, these variables:

$name = 'Fred';
$age = 35;
$wife = 'Betty';

Creating Variables from an Array

The extract( ) function automatically creates local variables from an array. The indexes of the array elements are the variable names:

extract($person); // $name, $age, and $wife are now set

If a variable created by the extraction has the same name as an existing one, the extracted variable overwrites the existing variable.

You can modify extract( )'s behavior by passing a second argument. Appendix A describes the possible values for this second argument. The most useful value is EXTR_PREFIX_SAME, which says that the third argument to extract( ) is a prefix for the variable names that are created. This helps ensure that you create unique variable names when you use extract( ). It is good PHP style to always use EXTR_PREFIX_SAME, as shown here:

$shape = "round";
$array = array("cover" => "bird", "shape" => "rectangular");
extract($array, EXTR_PREFIX_SAME, "book");
echo "Cover: $book_cover, Book Shape: $book_shape, Shape: $shape";
Cover: bird, Book Shape: rectangular, Shape: round

Creating an Array from Variables

The compact( ) function is the complement of extract( ). Pass it the variable names to compact either as separate parameters or in an array. The compact( ) function creates an associative array whose keys are the variable names and whose values are the variable's values. Any names in the array that do not correspond to actual variables are skipped. Here's an example of compact( ) in action:

$color = 'indigo';
$shape = 'curvy';
$floppy = 'none';

$a = compact('color', 'shape', 'floppy');
// or
$names = array('color', 'shape', 'floppy');
$a = compact($names);

Traversing Arrays

The most common task with arrays is to do something with every element--for instance, sending mail to each element of an array of addresses, updating each file in an array of filenames, or adding up each element of an array of prices. There are several ways to traverse arrays in PHP, and the one you choose will depend on your data and the task you're performing.

The foreach Construct

The most common way to loop over elements of an array is to use the foreach construct:

$addresses = array('spam@cyberpromo.net', 'abuse@example.com');
foreach ($addresses as $value) {
echo "Processing $value\n";
}
Processing spam@cyberpromo.net
Processing abuse@example.com

PHP executes the body of the loop (the echo statement) once for each element of $addresses in turn, with $value set to the current element. Elements are processed by their internal order.

An alternative form of foreach gives you access to the current key:

$person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Wilma');
foreach ($person as $k => $v) {
echo "Fred's $k is $v\n";
}
Fred's name is Fred
Fred's age is 35
Fred's wife is Wilma

In this case, the key for each element is placed in $k and the corresponding value is placed in $v.

The foreach construct does not operate on the array itself, but rather on a copy of it. You can insert or delete elements in the body of a foreach loop, safe in the knowledge that the loop won't attempt to process the deleted or inserted elements.

The Iterator Functions

Every PHP array keeps track of the current element you're working with; the pointer to the current element is known as the iterator. PHP has functions to set, move, and reset this iterator. The iterator functions are:

current( )
Returns the element currently pointed at by the iterator

reset( )
Moves the iterator to the first element in the array and returns it

next( )
Moves the iterator to the next element in the array and returns it

prev( )
Moves the iterator to the previous element in the array and returns it

end( )
Moves the iterator to the last element in the array and returns it

each( )
Returns the key and value of the current element as an array and moves the iterator to the next element in the array

key( )
Returns the key of the current element

The each( ) function is used to loop over the elements of an array. It processes elements according to their internal order:

reset($addresses);
while (list($key, $value) = each($addresses)) {
echo "$key is $value
\n";
}
0 is spam@cyberpromo.net
1 is abuse@example.com

This approach does not make a copy of the array, as foreach does. This is useful for very large arrays when you want to conserve memory.

The iterator functions are useful when you need to consider some parts of the array separately from others. Example 5-1 shows code that builds a table, treating the first index and value in an associative array as table column headings.

Example 5-1: Building a table with the iterator functions

$ages = array('Person' => 'Age',
'Fred' => 35,
'Barney' => 30,
'Tigger' => 8,
'Pooh' => 40);
// start table and print heading
reset($ages);
list($c1, $c2) = each($ages);
echo("\n");
// print the rest of the values
while (list($c1,$c2) = each($ages)) {
echo("\n");
}
// end the table
echo("
$c1$c2
$c1$c2
");





PersonAge
Fred35
Barney30
Tigger8
Pooh40


Using a for Loop

If you know that you are dealing with an indexed array, where the keys are consecutive integers beginning at 0, you can use a for loop to count through the indexes. The for loop operates on the array itself, not on a copy of the array, and processes elements in key order regardless of their internal order.

Here's how to print an array using for:

$addresses = array('spam@cyberpromo.net', 'abuse@example.com');
for($i = 0; $i < count($array); $i++) { $value = $addresses[$i]; echo "$value\n"; } spam@cyberpromo.net abuse@example.com

Calling a Function for Each Array Element
PHP provides a mechanism, array_walk( ), for calling a user-defined function once per element in an array: array_walk(array, function_name); The function you define takes in two or, optionally, three arguments: the first is the element's value, the second is the element's key, and the third is a value supplied to array_walk( ) when it is called. For instance, here's another way to print table columns made of the values from an array: function print_row($value, $key) { print("$value$key\n");
}
$person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Wilma');
array_walk($person, 'print_row');

A variation of this example specifies a background color using the optional third argument to array_walk( ). This parameter gives us the flexibility we need to print many tables, with many background colors:

function print_row($value, $key, $color) {
print("$value$key\n");
}
$person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Wilma');
array_walk($person, 'print_row', 'blue');

The array_walk( ) function processes elements in their internal order.

Reducing an Array

A cousin of array_walk( ), array_reduce( ), applies a function to each element of the array in turn, to build a single value:

$result = array_reduce(array, function_name [, default ]);

The function takes two arguments: the running total, and the current value being processed. It should return the new running total. For instance, to add up the squares of the values of an array, use:

function add_up ($running_total, $current_value) {
$running_total += $current_value * $current_value;
return $running_total;
}

$numbers = array(2, 3, 5, 7);
$total = array_reduce($numbers, 'add_up');
// $total is now 87

The array_reduce( ) line makes these function calls:

add_up(2,3)
add_up(13,5)
add_up(38,7)

The default argument, if provided, is a seed value. For instance, if we change the call to array_reduce( ) in the previous example to:

$total = array_reduce($numbers, 'add_up', 11);

The resulting function calls are:

add_up(11,2)
add_up(13,3)
add_up(16,5)
add_up(21,7)

If the array is empty, array_reduce( ) returns the default value. If no default value is given and the array is empty, array_reduce( ) returns NULL.

Searching for Values

The in_array( ) function returns true or false, depending on whether the first argument is an element in the array given as the second argument:

if (in_array(to_find, array [, strict])) { ... }

If the optional third argument is true, the types of to_find and the value in the array must match. The default is to not check the types.

Here's a simple example:

$addresses = array('spam@cyberpromo.net', 'abuse@example.com',
'root@example.com');
$got_spam = in_array('spam@cyberpromo.net', $addresses); // $got_spam is true
$got_milk = in_array('milk@tucows.com', $addresses); // $got_milk is false

PHP automatically indexes the values in arrays, so in_array( ) is much faster than a loop that checks every value to find the one you want.

Example 5-2 checks whether the user has entered information in all the required fields in a form.

Example 5-2: Searching an array

You ';
echo have_required($_POST, array('name', 'email_address')) ? 'did' : 'did not';
echo ' have all the required fields.

';
}
?>
" method="post">


Name:

Email address:

Age (optional):








A variation on in_array( ) is the array_search( ) function. While in_array( ) returns true if the value is found, array_search( ) returns the key of the found element:

$person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Wilma');
$k = array_search($person, 'Wilma');
echo("Fred's $k is Wilma\n");
Fred's wife is Wilma

The array_search( ) function also takes the optional third strict argument, which requires the types of the value being searched for and the value in the array to match.

Sorting

Sorting changes the internal order of elements in an array and optionally rewrites the keys to reflect this new order. For example, you might use sorting to arrange a list of scores from biggest to smallest, to alphabetize a list of names, or to order a set of users based on how many messages they posted.

PHP provides three ways to sort arrays--sorting by keys, sorting by values without changing the keys, or sorting by values and then changing the keys. Each kind of sort can be done in ascending order, descending order, or an order defined by a user-defined function.

Sorting One Array at a Time

The functions provided by PHP to sort an array are shown in Table 5-1.

Table 5-1: PHP functions for sorting an array

Effect


Ascending


Descending


User-defined order

Sort array by values, then reassign indexes starting with 0


sort( )


rsort( )


usort( )

Sort array by values


asort( )


arsort( )


uasort( )

Sort array by keys


ksort( )


krsort( )


uksort( )

The sort( ), rsort( ), and usort( ) functions are designed to work on indexed arrays, because they assign new numeric keys to represent the ordering. They're useful when you need to answer questions like "what are the top 10 scores?" and "who's the third person in alphabetical order?" The other sort functions can be used on indexed arrays, but you'll only be able to access the sorted ordering by using traversal functions such as foreach and next.

To sort names into ascending alphabetical order, you'd use this:

$names = array('cath', 'angela', 'brad', 'dave');
sort($names); // $names is now 'angela', 'brad', 'cath', 'dave'

To get them in reverse alphabetic order, simply call rsort( ) instead of sort( ).

If you have an associative array mapping usernames to minutes of login time, you can use arsort( ) to display a table of the top three, as shown here:

$logins = array('njt' => 415,
'kt' => 492,
'rl' => 652,
'jht' => 441,
'jj' => 441,
'wt' => 402);
arsort($logins);
$num_printed = 0;
echo("\n");
foreach ($logins as $user => $time ) {
echo("\n");
if (++$num_printed == 3) {
break; // stop after three
}
}
echo("
$user$time
\n");




rl652
kt492
jht441


If you want that table displayed in ascending order by username, use ksort( ):

ksort($logins);
echo("\n");
foreach ($logins as $user => $time) {
echo("\n");
}
echo("
$user$time
\n");







jht441
jj441
kt492
njt415
rl652
wt402


User-defined ordering requires that you provide a function that takes two values and returns a value that specifies the order of the two values in the sorted array. The function should return 1 if the first value is greater than the second, -1 if the first value is less than the second, and 0 if the values are the same for the purposes of your custom sort order.

Example 5-3 is a program that lets you try the various sorting functions on the same data.

Example 5-3: Sorting arrays

'Buzz Lightyear',
'email_address' => 'buzz@starcommand.gal',
'age' => 32,
'smarts' => 'some');

if($submitted) {
if($sort_type == 'usort' || $sort_type == 'uksort' || $sort_type == 'uasort') {
$sort_type($values, 'user_sort');
}
else {
$sort_type($values);
}
}
?>




Standard sort

Reverse sort

User-defined sort

Key sort

Reverse key sort

User-defined key sort

Value sort

Reverse value sort

User-defined value sort








Values :




    $value) {
    echo "
  • $key: $value
  • ";
    }
    ?>



Natural-Order Sorting

PHP's built-in sort functions correctly sort strings and numbers, but they don't correctly sort strings that contain numbers. For example, if you have the filenames ex10.php, ex5.php, and ex1.php, the normal sort functions will rearrange them in this order: ex1.php, ex10.php, ex5.php. To correctly sort strings that contain numbers, use the natsort( ) and natcasesort( ) functions:

$output = natsort(input);
$output = natcasesort(input);

Sorting Multiple Arrays at Once

The array_multisort( ) function sorts multiple indexed arrays at once:

array_multisort(array1 [, array2, ... ]);

Pass it a series of arrays and sorting orders (identified by the SORT_ASC or SORT_DESC constants), and it reorders the elements of all the arrays, assigning new indexes. It is similar to a join operation on a relational database.

Imagine that you have a lot of people, and several pieces of data on each person:

$names = array('Tom', 'Dick', 'Harriet', 'Brenda', 'Joe');
$ages = array(25, 35, 29, 35, 35);
$zips = array(80522, '02140', 90210, 64141, 80522);

The first element of each array represents a single record--all the information known about Tom. Similarly, the second element constitutes another record--all the information known about Dick. The array_multisort( ) function reorders the elements of the arrays, preserving the records. That is, if Dick ends up first in the $names array after the sort, the rest of Dick's information will be first in the other arrays too. (Note that we needed to quote Dick's zip code to prevent it from being interpreted as an octal constant.)

Here's how to sort the records first ascending by age, then descending by zip code:

array_multisort($ages, SORT_ASC, $zips, SORT_DESC, $names, SORT_ASC);

We need to include $names in the function call to ensure that Dick's name stays with his age and zip code. Printing out the data shows the result of the sort:

echo("\n");
for ($i=0; $i <>\n");
}
echo("
$ages[$i]$zips[$i]$names[$i]
\n");






2580522Tom
2990210Harriet
3580522Joe
3564141Brenda
3502140Dick


Reversing Arrays

The array_reverse( ) function reverses the internal order of elements in an array:

$reversed = array_reverse(array);

Numeric keys are renumbered starting at 0, while string indexes are unaffected. In general, it's better to use the reverse-order sorting functions instead of sorting and then reversing the order of an array.

The array_flip( ) function returns an array that reverses the order of each original element's key-value pair:

$flipped = array_flip(array);

That is, for each element of the array whose value is a valid key, the element's value becomes its key and the element's key becomes its value. For example, if you have an array mapping usernames to home directories, you can use array_flip( ) to create an array mapping home directories to usernames:

$u2h = array('gnat' => '/home/staff/nathan',
'rasmus' => '/home/elite/rasmus',
'ktatroe' => '/home/staff/kevin');
$h2u = array_flip($u2h);
$user = $h2u['/home/staff/kevin']; // $user is now 'ktatroe'

Elements whose original values are neither strings nor integers are left alone in the resulting array. The new array lets you discover the key in the original array given its value, but this technique works effectively only when the original array has unique values.

Randomizing Order

To traverse the elements in an array in a random order, use the shuffle( ) function. All existing keys, whether string or numeric, are replaced with consecutive integers starting at 0.

Here's how to randomize the order of the days of the week:

$days = array('Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday', 'Saturday', 'Sunday');
shuffle($days);
print_r($days);
Array
(
[0] => Tuesday
[1] => Thursday
[2] => Monday
[3] => Friday
[4] => Wednesday
[5] => Saturday
[6] => Sunday
)

Obviously, the order after your shuffle( ) may not be the same as the sample output here. Unless you are interested in getting multiple random elements from an array, without repeating any specific item, using the rand( ) function to pick an index is more efficient.

Acting on Entire Arrays

PHP has several useful functions for modifying or applying an operation to all elements of an array. You can merge arrays, find the difference, calculate the total, and more, all using built-in functions.

Calculating the Sum of an Array

The array_sum( ) function adds up the values in an indexed or associative array:

$sum = array_sum(array);

For example:

$scores = array(98, 76, 56, 80);
$total = array_sum($scores);
// $total = 310

Merging Two Arrays

The array_merge( ) function intelligently merges two or more arrays:

$merged = array_merge(array1, array2 [, array ... ])

If a numeric key from an earlier array is repeated, the value from the later array is assigned a new numeric key:

$first = array('hello', 'world'); // 0 => 'hello', 1 => 'world'
$second = array('exit', 'here'); // 0 => 'exit', 1 => 'here'
$merged = array_merge($first, $second);
// $merged = array('hello', 'world', 'exit', 'here')

If a string key from an earlier array is repeated, the earlier value is replaced by the later value:

$first = array('bill' => 'clinton', 'tony' => 'danza');
$second = array('bill' => 'gates', 'adam' => 'west');
$merged = array_merge($first, $second);
// $merged = array('bill' => 'gates', 'tony' => 'danza', 'adam' => 'west')

Calculating the Difference Between Two Arrays

The array_diff( ) function identifies values from one array that are not present in others:

$diff = array_diff(array1, array2 [, array ... ]);

For example:

$a1 = array('bill', 'claire', 'elle', 'simon', 'judy');
$a2 = array('jack', 'claire', 'toni');
$a3 = array('elle', 'simon', 'garfunkel');
// find values of $a1 not in $a2 or $a3
$diff = array_diff($a1, $a2, $a3);
// $diff is array('bill', 'judy');

Values are compared using ===, so 1 and "1" are considered different. The keys of the first array are preserved, so in $diff the key of 'bill' is 0 and the key of 'judy' is 4.

Filtering Elements from an Array

To identify a subset of an array based on its values, use the array_filter( ) function:

$filtered = array_filter(array, callback);

Each value of array is passed to the function named in callback. The returned array contains only those elements of the original array for which the function returns a true value. For example:

function is_odd ($element) {
return $element % 2;
}
$numbers = array(9, 23, 24, 27);
$odds = array_filter($numbers, 'is_odd');
// $odds is array(0 => 9, 1 => 23, 3 => 27)

As you see, the keys are preserved. This function is most useful with associative arrays.

Using Arrays

Arrays crop up in almost every PHP program. In addition to their obvious use for storing collections of values, they're also used to implement various abstract data types. In this section, we show how to use arrays to implement sets and stacks.

Sets

Arrays let you implement the basic operations of set theory: union, intersection, and difference. Each set is represented by an array, and various PHP functions implement the set operations. The values in the set are the values in the array--the keys are not used, but they are generally preserved by the operations.

The union of two sets is all the elements from both sets, with duplicates removed. The array_merge( ) and array_unique( ) functions let you calculate the union. Here's how to find the union of two arrays:

function array_union($a, $b) {
$union = array_merge($a, $b); // duplicates may still exist
$union = array_unique($union);

return $union;
}

$first = array(1, 'two', 3);
$second = array('two', 'three', 'four');
$union = array_union($first, $second);
print_r($union);
Array
(
[0] => 1
[1] => two
[2] => 3
[4] => three
[5] => four
)

The intersection of two sets is the set of elements they have in common. PHP's built-in array_intersect( ) function takes any number of arrays as arguments and returns an array of those values that exist in each. If multiple keys have the same value, the first key with that value is preserved.

Another common function to perform on a set of arrays is to get the difference; that is, the values in one array that are not present in another array. The array_diff( ) function calculates this, returning an array with values from the first array that are not present in the second.

The following code takes the difference of two arrays:

$first = array(1, 'two', 3);
$second = array('two', 'three', 'four');
$difference = array_diff($first, $second);
print_r($difference);
Array
(
[0] => 1
[2] => 3
)

Stacks

Although not as common in PHP programs as in other programs, one fairly common data type is the last-in first-out (LIFO) stack. We can create stacks using a pair of PHP functions, array_push( ) and array_pop( ). The array_push( ) function is identical to an assignment to $array[]. We use array_push( ) because it accentuates the fact that we're working with stacks, and the parallelism with array_pop() makes our code easier to read. There are also array_shift( ) and array_unshift( ) functions for treating an array like a queue.

Stacks are particularly useful for maintaining state. Example 5-4 provides a simple state debugger that allows you to print out a list of which functions have been called up to this point (i.e., the stack trace).

Example 5-4: State debugger

$call_trace = array( );

function enter_function($name) {
global $call_trace;
array_push($call_trace, $name); // same as $call_trace[] = $name

echo "Entering $name (stack is now: " . join(' -> ', $call_trace) . ')
';
}

function exit_function( ) {
echo 'Exiting
';

global $call_trace;
array_pop($call_trace); // we ignore array_pop( )'s return value
}

function first( ) {
enter_function('first');
exit_function( );
}

function second( ) {
enter_function('second');
first( );
exit_function( );
}

function third( ) {
enter_function('third');
second( );
first( );
exit_function( );
}

first( );
third( );

Here's the output from Example 5-4:

Entering first (stack is now: first)
Exiting
Entering third (stack is now: third)
Entering second (stack is now: third -> second)
Entering first (stack is now: third -> second -> first)
Exiting
Exiting
Entering first (stack is now: third -> first)
Exiting
Exiting

No comments:

Post a Comment