26 Aug 09 PHP Programming Tutorial: Arrays



PHP Arrays are complex variables that take a bunch of variables and store it under one variable. Arrays can be a little complicated so don’t feel bad if you have to come back to this tutorial again. You could think of an array like a box that you fit a bunch of variables (or even more arrays) inside. Just like organizing your home, you can store a bunch of related things in the same box (array). You may store information about a house, such as windows, doors, carpet, bedrooms, and bathrooms, in a single array called $HouseData.

CREATING AND VIEWING ARRAYS
Creating an array is similar to creating a variable. The difference with arrays is that you also assign a key value, also known as the index. Here’s a sample new array:

<?php
$carParts[0] = "Tires";
$carParts[1] = "Seats";
$carParts[2] = "Engine";
$carParts[3] = "Doors";
 
echo $carParts[0]; // Output "Tires"
?>

Now the array $carParts holds four values: Tires, Seats, Engine, and Doors. Here’s a quicker way to create the same array:

<?php
$carParts = array("Tires", "Seats", "Engine", "Doors");
?>

PHP automatically assigns the first string with a key value of 0, and then 1, and so on. If you want an array to start with another number, like 16, you can do this:

<?php
$carParts = array( 16 => "Tires", "Seats", "Engine", "Doors");
?>

You can also use strings in the array instead of numbers. This is called an associative array. Here’s an example:

<?php
$webSite["first"] = "PHP";
$webSite["middle"] = "Programming";
$webSite["last"] = "Tutorial";
 
echo $webSite["middle"]; // Outputs "Programming".
echo "<br />";
echo $webSite["first"] . " " . $webSite["last"]; // Outputs PHP Tutorial.
?>

You can even put an array inside an array:

<?php
$carParts = array("Tires", "Seats", array("Engine", "Doors"));
 
// This outputs "Tires" and adds a HTML break.
echo $carParts[0] . '<br />';
 
// PHP will tell you this is an array.
echo $carParts[2] . '<br />';
 
// This goes to the array in [2] and then goes inside of the inner array
// to [1], which is "Doors".
echo $carParts[2][1];
?>

Echoing an array is very similar to echoing a variable:

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

As expected, this outputs “Tires”.

Now let’s see how to echo an array that’s inside another array:

<?php
 
// We have an array inside another array.
$carParts = array("Tires", "Seats", array("Engine", "Doors"));
 
// This outputs "Tires" and adds a HTML break.
echo $carParts[0] . '<br />';
 
// PHP will tell you this is an array.
echo $carParts[2] . '<br />';
 
// This goes to the array in [2] and then goes inside of the inner array
// to [1], which is "Doors".
echo $carParts[2][1];
 
?>

So in other words, $carParts[2][1] tells PHP to look at the 3rd position in the array. Remember that arrays start with a 0. PHP finds another array at the 3rd position. So then PHP listens to the [1] and looks for the 2nd position of the inner array.

Go back to Building PHP Scripts.

Leave a Comment