php tutorials
Arrays
- To work with indexed arrays.
- To work with associative arrays.
- To work with two-dimensional arrays.
- 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.
Indexed Arrays
Indexed arrays are similar to tables with a single column. An indexed 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.
$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.
$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:
$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.
$Beatles[] = 'Nat';
Reading from Arrays
Reading from arrays is just a matter of pointing to a specific index or key.
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.
foreach ($Beatles as $Beatle)
{
echo "$Beatle<br>";
}
The above code snippets are combined in the following example.
Code Sample: Arrays/Demos/IndexedArrays.php
<html>
<head>
<title>Indexed Arrays</title>
</head>
<body>
<h1>Indexed 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>
Exercise: Working with Indexed Arrays
In this exercise, you will use arrays to create a
table with a single column that lists all your favorite
colors.
(see footnote) As shown in the screenshot below, the
background of each table row should be the same as the
color named in the row.
- Open Arrays/Exercises/ColorTable.php for editing.
- Create an array that holds your favorite colors.
- Inside of the open and close <table> tags, loop through the array outputting a table row for each element.
- Test your solution in a browser.
Associative Arrays
Whereas indexed 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 indexed arrays, we can intialize a zero-length associative array and then add elements.
$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.
$Beatles = array('singer1' => 'John',
'singer2' => 'Paul',
'guitarist' => 'George',
'drummer' => 'Ringo');
Reading from Associative Arrays
Reading from associative arrays is as simple as reading from indexed arrays.
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.
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.
Exercise: Working with Associative Arrays
In this exercise, you will use arrays to create a
table with two columns that lists all your favorite
colors and their hexadecimal equivalents. The background
of each table row should be the same as the color named
in the row as shown in the screenshot below.
- Open Arrays/Exercises/ColorTable2.php for editing.
- Create an associative array that holds color hex codes indexed by their color names, which can be found at http://www.w3schools.com/html/html_colornames.asp.
- After the existing table row, write code to loop through the array outputting a table row with two columns for each element in the array.
- Test your solution in a browser.
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.
$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, (see footnote) 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.
<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.
| 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.
Footnotes
-
See http://www.w3schools.com/html/html_colornames.asp for a list of color names.
-
Remember that the first row is row 0 and the first column is column 0.
-
For a complete list of array functions, see http://www.php.net/array.