Indexed Arrays

Contact Us or call 1-877-932-8228
Indexed Arrays

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[4] = '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>
Next