PHP Arrays
Previous | Table of Contents | Next |
PHP Functions | Working with Strings and Text in PHP |
Purchase and download the full PDF and ePub versions of this PHP eBook for only $8.99 |
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 array 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, and the type of key that is used to access an array element dictates the array type. 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 is assigned to a variable using the assignment 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 numerical key type array are accessed by referencing the variable containing the array, followed by the index into array of the required element enclosed in square brackets ([]). We can extend our previous example to display the value contained in the second element of the array (remember 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 position 1 of the array, in this case the string "Yellow".
Creating an Associative Array
As described earlier, an associative array assigns names to positions in the array. This provides a more human friendly way to access array elements than the numerical key approach outlined above. Once again, the array() function is used to create the array, with optional arguments to pre-initialize the array elements. In the case of associative arrays, the arguments are of the form key=>value where key is the name by which the element will be referenced, and value is the value to be stored in that position in the array.
Suppose we are creating an array to store bank customer information. We can assign a key name to each element 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.
Creating Multidimensional PHP Arrays
A multidimensional PHP array is nothing more than an array in which each array element is itself an array. A multidimensional array can, therefore, be thought of as a table, where each element in the parent array represents a row of the table and the elements of each child array represent the columns of the row.
The following PHP script provides an example of a multidimensional array where the books array is assigned an array for each element containing title and author information for each book:
<?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'); ?>
Accessing Elements in a Multidimensional PHP Array
To understand accessing elements of a multidimensional array it helps to continue 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 that records the current element. This pointer can be changed using the next, previous, reset and end functions. The reset and end functions move the pointer to the first and last elements of the array respectively. The next function moves the pointer on 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 possible to move 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 it using the appropriate index key. For example, to change the first 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 name 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 the 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 accessed 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>"; }
This will result in the following output:
Red Yellow Green Blue Indigo
For associative arrays the foreach keyword allows you to iterate through both the keys and the values using the following syntax:
foreach ($arrayName as $keyVariable=>$valueVariable)
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>"; }
This 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 element can be modified using the array_splice() function. The array_splice() function takes two mandatory and two optional 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 argument is 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 available algorithms are SORT_NUMERIC, SORT_STRING and SORT_REGULAR. If no sort type is specified, SORT_REGULAR is used.
Similarly array items can be 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
Function | Description |
---|---|
print_r | Prints the elements of an array to the output stream |
array_keys | Returns an array containing all the keys in an associative array |
array_search | Returns the key for given value in the array if value exists |
array_values | Returns an array containing all the values in an array |
in_array | Returns true or false depending on whether specified value is in array |
array_merge | Merge two or more arrays into a single array |
array_reverse | Reverse the order of elements in an array |
shuffle | Sorts the array elements into random order |
Summary
Arrays in PHP are one of the most powerful and flexible mechanisms for storing and manipulating lists of data. Much has been covered in this chapter to ensure that you have both an understanding of how to create arrays, and also the wide range of functions that are available to work with those arrays. Without arrays it would be very difficult to work with large numbers of associated variables.
Arrays will be used often in the course of developing web applications using PHP. Arrays are also often returned from many of the built-in PHP functions so taking the time to learn about them in this chapter will pay off many times over in the future.
Purchase and download the full PDF and ePub versions of this PHP eBook for only $8.99 |