PHP Simple Array Example

This page shows how to use PHP's arrays.


//there are two types of arrays: "regular" arrays and associative arrays
//this example shows how to create a regular array

//think of a regular array as just a list of variables all contained within one array variable
		

Defining Arrays

You define an array using PHP's built-in array() function

$arrPeople = array("Tandi", "Jack", "Susan", "Donny", "Michaela", "Joshua");
		

Debugging the Contents of Arrays

You can easily output the raw contents of an array using PHP's built-in print_r() function:

print_r($arrPeople);
		
Array
(
    [0] => Tandi
    [1] => Jack
    [2] => Susan
    [3] => Donny
    [4] => Michaela
    [5] => Joshua
)

Looping Through Arrays

you can loop through the contents of an array easily by using PHP's foreach() statement:

foreach ($arrPeople as $person) {
	echo $person . "<br />";
}
		
Tandi
Jack
Susan
Donny
Michaela
Joshua

Accessing an Individual Element in an Array

Simple arrays are indexed by numbers, starting from 0. Use an index number in brackets to access an individual element.

So $arrPeople[2] will hold the name of the third person in the list:

The third person in the list is: Susan