[ Team LiB ] Previous Section Next Section

Manipulating Arrays

You can now populate arrays and access their elements, but PHP has functions to help you do much more than that with arrays. If you're used to Perl, you'll find some of these eerily familiar!

Joining Two Arrays with array_merge()

array_merge() accepts two or more arrays and returns a merged array combining all their elements. In the following example, we create two arrays, joining the second to the first, and loop through the resultant third array:


$first = array("a", "b", "c");
$second = array(1,2,3);
$third = array_merge( $first, $second );

foreach ( $third as $val ) {
  print "$val<br />";
}

The $third array contains copies of all the elements of both the $first and $second arrays. The foreach statement prints this combined array ('a', 'b', 'c', 1, 2, 3) to the browser with a <br /> tag between each element. Remember that the arrays passed to array_merge() are not themselves transformed. If two arrays passed to array_merge() have elements with the same string index, those of the first array are overwritten by their namesakes in the second.

Adding Multiple Variables to an Array

array_push() accepts an array and any number of further parameters, each of which is added to the array. Note that the array_push() function is unlike array_merge() in that the array passed in as the first argument is transformed. array_push() returns the total number of elements in the array. Let's create an array and add some more values to it:


$first = array ("a", "b", "c");
$total = array_push( $first, 1, 2, 3 );

print "There are $total elements in \$first<p>";
foreach ( $first as $val ) {
  print "$val<br/>";
}
print "</p>";

Because array_push() returns the total number of elements in the array it transforms, we can store this value (6) in a variable and print it to the browser. The $first array now contains its original elements as well the three integers we passed to the array_push() function. All of these are printed to the browser within the foreach statement.

Notice that we used a backslash character when we printed the string "\$first". If you use a dollar sign followed by numbers and letters within a string, PHP attempts to insert the value of a variable by that name. In the previous example, we wanted to print the string '$first' rather than the value of the $first variable. To print the special character $, therefore, we must precede it with a backslash. PHP will now print the character instead of interpreting it. This process is often referred to as escaping a character.

graphics/watchout_icon.gif

Perl users beware! If you're used to working with Perl's push(), you should note that, if you pass a second array variable to array_push(), it will be added as a single element, creating a multidimensional array. If you want to combine two arrays, use array_merge().


If you need to add new elements to the beginning of an array, you can use the array_unshift() function, which accepts an array and any number of additional values. It will add the value arguments to the start of the given array. The following amends our previous fragment to use array_unshift():


$first = array ("a", "b", "c");
$total = array_unshift( $first, 1, 2, 3 );

$first now contains the following:


1, 2, 3, "a", "b", "c"

array_unshift() returns the new size of the array it transforms.

Removing the First Element of an Array with array_shift()

array_shift() removes and returns the first element of an array passed to it as an argument. In the following example, we use array_shift() in conjunction with a while loop. We test the value returned from count() to check whether the array still contains elements:


<?php
$an_array = array("a", "b", "c");

while ( count( $an_array ) ) {
  $val = array_shift( $an_array);
  print "$val<br />";
  print "there are ".count( $an_array )." elements in \$an_array <br />";
}
?>

You can see the output from this fragment of code in Figure 7.4.

Figure 7.4. Using array_shift() to remove and print every element in an array.

graphics/07fig04.gif

array_shift() is useful when you need to create a queue and act on it until the queue is empty.

Slicing Arrays with array_slice()

array_slice() enables you to extract a chunk of an array. It accepts an array as an argument, a starting position (offset), and a length (optional). If the length is omitted, array_slice() generously assumes that you want all elements from the starting position onward returned. array_slice() does not alter the array you pass to it; it returns a new array containing the elements you have requested.

In the following example, we create an array and extract a new three-element array from it:


$first = array ("a", "b", "c", "d", "e", "f");
$second = array_slice($first, 2, 3);

foreach ( $second as $var ) {
  print "$var<br />";
}

This prints the elements 'c', 'd', and 'e', separating each by a <br /> tag. Notice that the offset is inclusive if we think of it as the index number of the first element we are requesting. In other words, the first element of the $second array is equivalent to $first[2].

If we pass array_slice() an offset argument that is less than zero, the returned slice begins that number of elements from the end of the given array.

If we pass array_slice() a length argument that is less than zero, the returned slice contains all elements from the offset position to that number of elements from the end of the given array.

    [ Team LiB ] Previous Section Next Section