You are on page 1of 1

Chapter 3 How to Write PHP Scripts

26

Individual itemsor array elementsare identified by means of a number in square brackets


immediately
following the variable name. PHP assigns the number automatically, but its important to note that the
numbering
always begins at 0. So the first item in the array, wine in our example, is referred to as
$shoppingList[0], not
$shoppingList[1]. And although there are five items, the last one (cheese) is $shoppingList[4]. The
number is
referred to as the array key or index, and this type of array is called an indexed array.
PHP uses another type of array in which the key is a word (or any combination of letters and numbers).
For
instance, an array containing details of this book might look like this:
$book['title'] = 'PHP Solutions: Dynamic Web Design Made Easy, Third Edition';
$book['author'] = 'David Powers';
$book['publisher'] = 'Apress';
$book['ISBN'] = '978-1-4842-0636-2';
This type of array is called an associative array. Note that the array key is enclosed in quotes (single
or double, it
doesnt matter). It shouldnt contain any spaces or punctuation, except for the underscore.
Arrays are an important and useful part of PHP. Youll use them a lot, starting with the next chapter,
when youll
store details of images in an array to display a random image on a webpage. Arrays are also used
extensively with
databases as you fetch the results of a search in a series of arrays.

Note You can learn the various ways of creating arrays in the second half of this chapter.

PHPs Built-in Superglobal Arrays

PHP has several built-in arrays that are automatically populated with useful information. They are
called superglobal
arrays, and all begin with a dollar sign followed by an underscore. Two that you will see frequently are
$_POST and
$_GET. They contain information passed from forms through the Hypertext Transfer Protocol (HTTP)
post and get
methods, respectively. The superglobals are all associative arrays, and the keys of $_POST and $_GET
are automatically
derived from the names of form elements or variables in a query string at the end of a URL.
Lets say you have a text input field called "address" in a form; PHP automatically creates an array
element called
$_POST['address'] when the form is submitted by the post method or $_GET['address'] if you use the
get method.
As Figure 3-4 shows, $_POST['address'] contains whatever value a visitor enters in the text field,
enabling you to
display it onscreen, insert it in a database, send it to your email inbox, or do whatever you want with it.

You might also like