PHP Arrays

Revision as of 19:37, 1 June 2007 by Neil (Talk | contribs) (Sorting an Array)

Revision as of 19:37, 1 June 2007 by Neil (Talk | contribs) (Sorting an Array)

PHP Arrays provide a way to group together many variables such that they can be referenced and manipulated using a single variable. An array is, in many ways, a self-contained list of variables.

Once an array has been created items can be added, removed and modified, sorted and much more. The items in an arrasy can be of any variable type and an array can contain any mixture of data types - it is not necessary to have each element in the array of the same type.

Elements of an array are accessed using a key. There are two types of array depending on the type of key that is used to access an array element. In a numerical key array elements are accessed by specifying the numerical position of the item in the array. The first item in an array is element 0, the second is element 1 and so on. The second type of array is the associative array where a name is given to each element and that name is used to access the corresponding array element.

Create a PHP Array

Arrays are created using the array() function. The array() function takes zero or more arguments and returns the new array which must be assigned to a variable using the assigment operator (=). If arguments are provided they are used to initialize the array with data.

PHP arrays grow and shrink dynamically as items are added and removed so it is not necessary to specify the array size at creation time as it is with some other programming languages.

We can create an empty array as follows:

<?php
      $colorArray = array();
?>

Alternatively, we can create an array pre-initialized with values by providing the values as arguments to the array() function:

<?php
      $colorArray = array("Red", "Yellow", "Green", "Blue", "Indigo");
?>

Accessing Elements in a PHP Array

The elements in a PHP array using a numberical key are accessed by referencing the variable contain ing the array, followed by the index into array of the required element enclose din square brackets ([]). We can extend our previous example to display the value contained in the second element of the array (remmeber that the index is zero based so the first element is element 0:

<?php
      $colorArray = array("Red", "Yellow", "Green", "Blue", "Indigo");
    
      echo $colorArray[1];
?>

The above echo command will output the value in index postion 1 of the array, in this case the string "Yellow".


Creating an Associative Array

As described earlier an associative array assigns names to postions in the array. This provides a more human friendly way to access arrasy elements that the numerical key approach outlined above. Once again the array() function is used to create the array, with option arguments to pre-initialize the array elements. In the case of associative arrasy the arguments are of the form key=>value where key is the name by which the elemt will be referenced, and value is the value to be stored in taht position in the array.

Suppose we are creating an array to store bank customer information. We can assign a key name to each elelemt in the array as follows:

<?php
$customerArray = array('customerName'=>'John Smith', 'customerAddress'=>'1 The Street', 'accountNumber'=>'123456789');
?>

Accessing Elements of an Associative Array

Now that we have created an associative array and assigned names to each element we can use those names to access the corresponding array values. We can, therefore extend our previous example to extract the customer name from our $customerArray:

<?php
      $customerArray = array('customerName'=>'John Smith', 'customerAddress'=>'1 The Street', 'accountNumber'=>'123456789');

      echo $customerArray['customerName'];
?>

The result will be the customer name "John Smith" appearing in the browser window.

Accessing Elements in a Multidimensional PHP Array

To understand accessing elements of a multidimensional array it heslp to continuew to use the table analogy we started in the last section. Assuming a multidimensional array, we need to first specify the array row that we wish to access. Secondly we need to specify the column in that row. To access an element, therefore we specify the array name and then follow it with the desired row and column of the array, each enclosed in square brackets ([]).

For example, suppose we wish to access the author of the second book in our $books array:

<?php
        $books = array();
        $books[0] = array('title'=>'JavaScript in 24 Hours', 'author'=>'Moncur');
        $books[1] = array('title'=>'JavaScript Unleashed', 'author'=>'Wyke');
        $books[2] = array('title'=>'Network+ Second Edition', 'author'=>'Harwood');

        echo $books[1]['author'];
?>

The echo will output "Wyke" which is in the author column of the second row of the array.

Using PHP Array Pointers

PHP arrays maintain an internal pointer which records the current element. This popinter can be changed using the next, previous, reset and end functions. The reset and end function moves the pointer to the first and last elememts of the array respectively. The next function moves the pointer onm to the next array element. The prev moves the pointer to the previous array element. The next and prev functions return false when it is not possibel to movbe any further in the corresponding direction.

Each function takes the name of the array in which the pointer adjustment is to take place as an argument:

<?php
      $colorArray = array("Red", "Yellow", "Green", "Blue", "Indigo");

      echo 'The last element is ' . end($colorArray) . '<br>';
      echo 'The previous element is ' .  prev($colorArray) . '<br>';
      echo 'The first element is ' . reset($colorArray) . '<br>';
      echo 'The next element is ' . next($colorArray) . '<br>';
?>

The above example will display the following output:

The last element is Indigo
The previous element is Blue
The first element is Red
The next element is Yellow

Changing, Adding and Removing PHP Array Elements

An array element can be changed by assigning a new value to using the appropriate index key. For example to change teh firsty element of an array:

$colorArray = array("Red", "Yellow", "Green", "Blue", "Indigo");

$colorArray[0] = "Orange";

A new item can be added to the end of an array using the array_push() function. This function takes two arguments, the first being the name of the array and the second the value to be added:

$colorArray = array("Red", "Yellow", "Green", "Blue", "Indigo");

array_push($colorArray, "White");

A new element can be inserted at the start of the array using the array_shift() function which takes the array anem and the value to be added as arguments:

$colorArray = array("Red", "Yellow", "Green", "Blue", "Indigo");

array_shift($colorArray, "White"); // Add White to start of array

The last item added to an array can be removed from the array using the array_pop() function. The following example removes the last element added:

$colorArray = array("Red", "Yellow", "Green", "Blue", "Indigo");

array_push($colorArray, "White"); // Add White to end of array

array_pop($colorArray); // Remove White from the end of teh array

The first item in the array can be removed using the array_unshift() function:

$colorArray = array("Red", "Yellow", "Green", "Blue", "Indigo");

array_shift($colorArray, "White"); // Add White to start of array

array_unshift($colorArray) // Remove White from the start of the array

Looping through PHP Array Elements

It is often necessary to loop through each element of an array to either read or change the values contained therein. There are a number of ways that this can be done.

One such mechanism is to use the foreach loop. The foreach loop works much like a for or while loop and allows you to iterate through each array element. There are two ways to use foreach. The first assigns the value of the current element to a specified variable which can then be acessed in the body of the loop. The syntax for this is:

foreach ($arrayName as $variable)

For example:

      $colorArray = array("Red", "Yellow", "Green", "Blue", "Indigo");

      foreach ($colorArray as $color)
      {
          echo "$color <br>";
      }

Will result in the following output:

Red
Yellow
Green
Blue
Indigo 

For associative arrays the foreach command allows you to iterate through both the keys and the values using the following syntax:

foreach ($arrayName as $variable)

For example:

      $customerArray = array('customerName'=>'John Smith', 'customerAddress'=>'1 The Street', 'accountNumber'=>'123456789');

        foreach ($customerArray as $key=>$value)
        {
                echo "Key = $key <br>";
                echo "Value = $value <br>";
        }

will result in the following output:

Key = customerName
Value = John Smith
Key = customerAddress
Value = 1 The Street
Key = accountNumber
Value = 123456789 

Replacing Sections of an Array

Entire blocks of array elemenst can be modified using the array_splice() function. The array_splice() function takes two mandatory and two option arguments. The first argument is the name of the array on which the function is to work. The second argument specifies the index into the array where the splice is to take effect. The optional third argument specifies the end point of the splice (if the third argument is omitted the end of the array is assumed). The final argumen tis an optional array containing elements to be used to replace the removed items.

The following example creates and initializes an array, then creates an array of replacement elements before using the splice function:


        $myArray = array ('One', 'Two', 'Three', 'Four', 'Five');

        $myReplacements  = array ('Six', 'Seven', 'Eight');

        $extract = array_splice ($myArray, 2, 4, $myReplacements);

The above example uses the array_splice() function to replace the Three, Four and Five with the Six, Seven and Eight from the $myReplacements array.

Sorting a PHP Array

An array can be sorted using the sort function. A number of different sorts are possible using the sort function. The function takes two arguments. The first argument is the name of the array. The second indicates the sort algorithm to use. the avialable algorithms are SORT_NUMERIC, SORT_STRING and SORT_REGULAR. If no sort type is specified, SORT_REGULAR is used.

Similarly array items can can sorted in descending order using the rsort function.

For example we can sort our array of color names:

$colorArray = array("Red", "Yellow", "Green", "Blue", "Indigo");
sort($colorArray, SORT_STRING);

It is also possible to perform a Natural Sort using the natsort function.

Sorting Associative Arrays

Associative arrays can be sorted in two ways, either by key or by value. To sort by key use ksort and krsort (reverse sort). To sort by value use the asort and arsort functions. The syntax and options for these functions are as outlined for the sort and rsort functions above.

Getting Information About PHP Arrays & other Array Functions

There are number of useful functions which can be used to obtain information about PHP arrays and also some function that have noit been covered in detail in this chapter. The following table lists these functions and provides descriptions:

FunctionDescription
print_rPrints the elements of an array to the output stream
array_keysReturns an array contaning all the keys in an associative array
array_searchReturns the key for given value in the array if value exists
array_valuesReturns an array contaning all the values in an array
in_arrayReturns true ot false depneding on whether specified value is in array
array_mergeMerge two or more arrays into a single array
array_reverseReverse the roder of elemenst in an array