| Fruity Pizza |
Thus far, the variables we've discussed contained only a single value, such as:
$i = 5;
However, array variables are a different kettle of fish altogether. An array is a complex variable that allows you to store multiple values in a single variable (which is handy when you need to store and represent related information). Think of the array variable as a "container" variable, which can contain one or more values. For example:
// define an array
$pizzaToppings = array('onion', 'tomato', 'cheese', 'anchovies', 'ham', 'pepperoni');
Here, $pizzaToppings is an array variable, which contains the values 'onion', 'tomato', 'cheese', 'anchovies', 'ham' and 'pepperoni'. (Array variables are particularly useful for grouping related values together.)
print_r() is a special function that allows you to take a sneak peek inside an array. It's more useful for debugging (finding out why your script doesn't work) than it is for display purposes, but I'll use it here so you can see what's going on under the surface. You do have your server running and your browser open, right?
The various elements of the array are accessed via an index number, with the first element starting at zero. So, to access the element 'onion', you would use the notation $pizzaToppings, while 'anchovies' would be $pizzaToppings - essentially, the array variable name followed by the index number enclosed within square braces.
PHP also allows you to replace indices with user-defined "keys", in order to create a slightly different type of array. Each key is unique, and corresponds to a single value within the array.
// define an array
$fruits = array('red' => 'apple', 'yellow' => 'banana', 'purple' => 'plum', 'green' => 'grape');
In this case, $fruits is an array variable containing four key-value pairs. (The => symbol is used to indicate the association between a key and its value.) In order to access the value 'banana', you would use the notation $fruits['yellow'], while the value 'grape' would be accessible via the notation $fruits['green'].
This type of array is sometimes referred to as a "hash" or "associative array". If you've ever used Perl, you'll see the similarities to the Perl hash variable.
How to do Everything with PHP & MySQL
How to do Everything with PHP & MySQL, the best-selling book by Melonfire, explains how to take full advantage of PHP's built-in support for MySQL and link the results of database queries to Web pages. You'll get full details on PHP programming and MySQL database development, and then you'll learn to use these two cutting-edge technologies together. Easy-to-follow sample applications include a PHP online shopping cart, a MySQL order tracking system, and a PHP/MySQL news publishing system.
Read more, or grab your copy now!