PHP Tutorial
Loading

Arrays

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.

Lesson Goals

  • To work with indexed arrays.
  • To work with associative arrays.
  • To work with two-dimensional arrays.
  • To work with array-manipulation functions.

Lesson Activities

  1. Indexed Arrays
  2. Associative Arrays
  3. Two-dimensional Arrays
  4. Array Manipulation Functions

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.

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/IndexedArrays.php
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<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>

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.

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 indexed 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
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<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();
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<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].

Remember that the first row is row 0 and the first column is column 0.

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
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<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.

For a complete list of array functions, see http://www.php.net/array

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.

Continue to the next lesson on PHP and HTML Forms »

This page was last updated on 2022-05-20

All pages and graphics in this PHP Tutorial is copyright 2013 and are the property of learnphp-tutorial.com unless otherwise specified. The purpose of this website is to help you learn PHP on your own and use of the website implies your agreement to our Terms of Service.