Arrays are special forms of variables. Whereas variables can only hold one value at a time – a string of text, a numeral, true or false – arrays can hold multiple values at the same time, each individually addressable. Variables are tiny delicate porcelain teacups; arrays are ice cube trays that can be expanded infinitely.

Arrays can be created for you – many system variables in PHP are actually arrays – or you can create them yourself:

<?php $beatles = array("John","Paul","Ringo","George"); ?>

In an ordinary array, each “slot” in the array is given a number, indexed from 0. To gain the name of the first member of the $beatles array, you would use:

<?php echo $beatles[0]; ?>

It is also possible to create an associative array, in which words are used to label the slots, rather than numbers. Again, many of these are system variables that are created for you, but you can equally create your own keys for your own associative array:

<?php $beatles_instruments = array("John" => "guitar", "Paul" => "bass", "Ringo" => "drums", "George" => "lead guitar"); ?>

To learn what instrument Paul played, you would echo $beatles_instruments["Paul"]; where “Paul” is the key. To print out the entire contents of an array, use print_r:

<?php print_r($beatles_instruments); ?>

As I mentioned, many server or system variables are arrays. There is an associative array for the browser used, as reported to the server when making a request of any document:

<?php echo $HTTP_SERVER_VARS['HTTP_USER_AGENT']; ?>

This could be shortened to:

<?php echo$_SERVER['HTTP_USER_AGENT']; ?>

Associative arrays are created from the name attribute value and entered data in forms when the user presses the submit button. So given this structure:

<form action="formhandler.php" method="post">
	<fieldset>
		<legend>Please supply the following information</legend>
		<label for="firstname" accesskey="f">First Name</label>
		<input type="text" name="firstname" id="firstname">
		<input type="submit" value="Submit">
	</fieldset>
</form>

When the submit button is pressed and formhandler.php is reached, the value of first name will be placed in an array. We can get this value on formhandler.php via:

<?php echo $HTTP_POST_VARS['firstname']; ?>

This can also be shortened to:

<?php echo $_POST['firstname']; ?>

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.