Arrays

In this lesson of the PHP tutorial, you will learn...
  1. To work with enumerated arrays.
  2. To work with associative arrays.
  3. To work with two-dimensional arrays.
  4. To work with array-manipulation functions.

Up to this point, we have dealt only with variables that store single values, called scalar variables. In this lesson, we will be covering arrays. Arrays are variables that store sets of values.

Enumerated Arrays

Enumerated arrays are similar to tables with a single column. An enumerated array can contain zero or more elements. In PHP, like in many programming languages, the first element of an array is in the "zeroeth" position. An array with no elements has a zero length.

Initializing Arrays

Arrays are initialized with the array() function, which can take a list of comma-delimited values that become the elements in the new array. The following lines of code initializes a zero-length array and then adds four elements to the array.

Syntax
$Beatles = array();
$Beatles[0] = 'John';
$Beatles[1] = 'Paul';
$Beatles[2] = 'George';
$Beatles[3] = 'Ringo';

The first line above is actually optional as the second line will create the array if one does not already exist. However, it is a better coding practice to explicitly initialize the array. The $Beatles array could also be created in a single line as follows.

Syntax
$Beatles = array('John','Paul','George','Ringo');

Appending to an Array

If you know how many elements are in an array, you can append to the array by specifying the index. For example, you could append to the $Beatles array shown above as follows:

Syntax
$Beatles[5] = 'Nat';

However, sometimes you don't know how many elements are in an array. Although you can easily figure this out, doing so requires an extra step. PHP provides an easy way of appending to an array of any length. Simply leave out the index.

Syntax
$Beatles[] = 'Nat';

Reading from Arrays

Reading from arrays is just a matter of pointing to a specific index or key.

Syntax
echo $Beatles[2]; //outputs George to the browser

Looping through Arrays

The following code will loop through the entire $Beatles array outputting each element to the browser.

Syntax
foreach ($Beatles as $Beatle)
{
 echo "$Beatle<br>";
}

The above code snippets are combined in the following example.

Code Sample: Arrays/Demos/EnumeratedArrays.php

<html>
<head>
<title>Enumerated Arrays</title>
</head>

<body>
<h1>Enumerated Arrays</h1>
<?php
 $Beatles = array();
 $Beatles[0] = 'John';
 $Beatles[1] = 'Paul';
 $Beatles[2] = 'George';
 $Beatles[3] = 'Ringo';
 
 echo $Beatles[2]; //outputs George to the browser
 
 $Beatles[] = 'Nat';
?>
<hr/>
<?php
 foreach ($Beatles as $Beatle)
 {
  echo "$Beatle<br/>";
 }
?>
</body>
</html>

Associative Arrays

Whereas enumerated arrays are indexed numerically, associative arrays are indexed using names. For example, instead of Ringo being indexed as 3, he could be indexed as "drummer".

Initializing Associative Arrays

Like with enumerated arrays, we can intialize a zero-length associative array and then add elements.

Syntax
$Beatles = array();
$Beatles['singer1'] = 'Paul';
$Beatles['singer2'] = 'John';
$Beatles['guitarist'] = 'George';
$Beatles['drummer'] = 'Ringo';

Or the array could be created in a single line as follows.

Syntax
$Beatles = array('singer1' => 'John',
                 'singer2' => 'Paul',
                 'guitarist' => 'George',
                 'drummer' => 'Ringo');

Reading from Associative Arrays

Reading from associative arrays is as simple as reading from enumerated arrays.

Syntax
echo $Beatles['drummer']; //outputs Ringo to the browser

Looping through Associative Arrays

The following code will loop through the entire $Beatles array outputting each element and its key to the browser.

Syntax
foreach ($Beatles as $key => $Beatle)
{
 echo "<b>$key:</b> $Beatle<br>";
}

The above code snippets are combined in the following example.

Code Sample: Arrays/Demos/AssociativeArrays.php

<html>
<head>
<title>Associative Arrays</title>
</head>

<body>
<h1>Associative Arrays</h1>
<?php
 $Beatles = array('singer1' => 'John',
     'singer2' => 'Paul',
     'guitarist' => 'George',
     'drummer' => 'Ringo');

 echo $Beatles['drummer']; //outputs Ringo to the browser
?>
<hr/>
<?php
 foreach ($Beatles as $key => $Beatle)
 {
  echo "<b>$key:</b> $Beatle<br/>";
 }
?>
</body>
</html>

Superglobal Arrays

The superglobal arrays are associative arrays. The file below outputs all the contents of the superglobal arrays using foreach loops.

Code Sample: Arrays/Demos/SuperGlobals.php

<?php
 session_start();
?>
<html>
<head>
<title>Superglobal Arrays</title>
</head>

<body>
<h1>Superglobal Arrays</h1>
<h2>$_COOKIE</h2>
<ol>
<?php
 foreach ($_COOKIE as $key => $item)
 {
  echo "<li><b>$key:</b> $item<br/></li>";
 }
?>
</ol>
<hr/>
<h2>$_ENV</h2>
<ol>
<?php
 foreach ($_ENV as $key => $item)
 {
  echo "<li><b>$key:</b> $item<br/></li>";
 }
?>
</ol>
<hr/>
<h2>$_FILES</h2>
<ol>
<?php
 foreach ($_FILES as $key => $item)
 {
  echo "<li><b>$key:</b> $item<br/></li>";
 }
?>
</ol>
<hr/>
<h2>$_GET</h2>
<ol>
<?php
 foreach ($_GET as $key => $item)
 {
  echo "<li><b>$key:</b> $item<br/></li>";
 }
?>
</ol>
<hr/>
<h2>$_POST</h2>
<ol>
<?php
 foreach ($_POST as $key => $item)
 {
  echo "<li><b>$key:</b> $item<br/></li>";
 }
?>
</ol>
<hr/>
<h2>$_REQUEST</h2>
<ol>
<?php
 foreach ($_REQUEST as $key => $item)
 {
  echo "<li><b>$key:</b> $item<br/></li>";
 }
?>
</ol>
<hr/>
<h2>$_SESSION</h2>
<ol>
<?php
 foreach ($_SESSION as $key => $item)
 {
  echo "<li><b>$key:</b> $item<br/></li>";
 }
?>
</ol>
<hr/>
<h2>$_SERVER</h2>
<ol>
<?php
 foreach ($_SERVER as $key => $item)
 {
  echo "<li><b>$key:</b> $item<br/></li>";
 }
?>
</ol>
</body>
</html>

Don't worry about the session_start() statement at the top. We'll cover that in detail later in the course.

Two-dimensional Arrays

In PHP, two-dimensional arrays are arrays that contain arrays. You can think of the outer array as containing the rows and the inner arrays as containing the data cells in those rows. For example, a two-dimensional array called $Rockbands could contain the names of the bands and some of the songs that they sing. Below is a grid that represents such a two-dimensional array.

Rockband Song1 Song2 Song3
Beatles Love Me Do Hey Jude Helter Skelter
Rolling Stones Waiting on a Friend Angie Yesterday's Papers
Eagles Life in the Fast Lane Hotel California Best of My Love

The following code creates this two-dimensional array. The internal arrays are highlighted. Note that the header row is not included.

Syntax
$Rockbands = array(
 array('Beatles','Love Me Do', 'Hey Jude','Helter Skelter'),
 array('Rolling Stones','Waiting on a Friend','Angie',
   'Yesterday\'s Papers'),
 array('Eagles','Life in the Fast Lane','Hotel California',
   'Best of My Love')
)

Reading from Two-dimensional Arrays

To read an element from a two-dimensional array, you must first identify the index of the "row" and then identify the index of the "column." For example, the song "Angie" is in row 1, column 2, so it is identified as $Rockbands[1][2].

Looping through Two-dimensional Arrays

To loop through a two-dimensional array, you need to nest one loop inside of another. The following code will create an HTML table from our two-dimensional array.

Syntax
<table border="1">
<?php
foreach($Rockbands as $Rockband)
{
 echo "<tr>";
 foreach($Rockband as $item)
 {
  echo "<td>$item</td>";
 }
 echo "</tr>";
}
?>
</table>

The above code snippets are combined in the following example to output a Rockbands table.

Code Sample: Arrays/Demos/TwoDimensionalArrays.php

<html>
<head>
<title>Two-dimensional Arrays</title>
</head>

<body>
<h1>Two-Dimensional Arrays</h1>
<?php
$Rockbands = array(
 array('Beatles','Love Me Do', 'Hey Jude','Helter Skelter'),
 array('Rolling Stones','Waiting on a Friend','Angie','Yesterday\'s Papers'),
 array('Eagles','Life in the Fast Lane','Hotel California','Best of My Love')
);
?>
<table border="1">
<tr>
 <th>Rockband</th>
 <th>Song 1</th>
 <th>Song 2</th>
 <th>Song 3</th>
</tr>
<?php
foreach($Rockbands as $Rockband)
{
 echo '<tr>';
 foreach($Rockband as $item)
 {
  echo "<td>$item</td>";
 }
 echo '</tr>';
}
?>
</table>
</body>
</html>

Array Manipulation Functions

The following table shows some of the more common array manipulation functions.

Useful Array Functions
Function Explanation
sort() Sorts an array alphabetically. Elements will be assigned to new index numbers.
asort() Sorts associative arrays alphabetically by value. The index association remains intact.
ksort() Sorts associative arrays alphabetically by key. The index association remains intact.
rsort() Reverse sorts an array alphabetically. Elements will be assigned to new index numbers.
arsort() Reverse sorts associative arrays alphabetically by value. The index association remains intact.
krsort() Reverse sorts associative arrays alphabetically by key. The index association remains intact.
shuffle() Randomly sorts the array. For the order to be sorted differently each time, the random number generator needs to be seeded with rsand().
array_reverse() Returns an array with the elements in reverse order.
array_walk() Applies a user function to every element of an array.
count() Returns the number of elements in an array.
explode() Converts a string to an array by splitting it on a specified separator.
is_array() Takes one parameter and returns true or false depending on whether the parameter passed is an array.
array_keys() Returns all the keys of an associative array as an array.
array_key_exists() Checks to see if a specified key exists in an array.

Arrays Conclusion

Arrays are an important feature of many modern programming languages. In this lesson, we have covered the most common uses of arrays.

To continue to learn PHP go to the top of this page and click on the next lesson in this PHP Tutorial's Table of Contents.

Use of this website implies agreement to the following:

Copyright Information

All pages and graphics on this Web site are the property of Webucator, Inc. unless otherwise specified.

None of the content on this website may be redistributed or reproduced in any way, shape, or form without written permission from Webucator, Inc.

No Printing or saving of web pages

This content may not be printed or saved. It is for online use only.


Linking to this website

You may link to any of the pages on this website; however, you may not include the content in a frame or iframe without written permission from Webucator, Inc.


Warranties

This website is provided without warranty of any kind. There are no guarantees that use of the site will not be subject to interruptions. All direct or indirect risk related to use of the site is borne entirely by the user. All code and explanations provided on this site are provided without warranties to correctness, performance, fitness, merchantability, and/or any other warranty (whether expressed or implied).

For individual private use only

You agree not to use this online manual to deliver or receive training. If you are delivering or attending a class that is making use of this online manual, you are in violation of our terms of service. Please report any abuse to courseware@webucator.com. If you would like to deliver or receive training using this manual, please fill out the form at http://www.webucator.com/Contact.cfm.