Blake O'Hare .com

PHP Tutorial Part 5 - Arrays

So far we've talked about storing numbers and strings into variables. There's another data type that's also quite useful called the array.

Arrays are basically lists of data that you can store into one variable. A list is constructed with a function aptly named "array"...

$items = array("This", "is", "a", "list", "of", "words");

Although this isn't the only way to create arrays. There is another function called "explode" that will take a string and separate it into an array based on a delimiter you specify.

$items = explode(" ", "This is a list of words");

This code and the one above it will yield the same result. Once you have an array, there are a few ways to add to it. First is a function called array_push which will add an item to the end of an array.

$items = array("This", "is", "a", "list", "of");
array_push($items, "words");

And the other way is to merge two arrays with array_merge

$items_a = array("This", "is", "a");
$items_b = array("list", "of", "words");
$items = array_merge($items_a, $items_b);

Again, these code samples yield the same result as the first few examples.

So the burning question is, why use arrays? Arrays allow you to put your data in a consistent form. This makes it easier to loop through it and do the same operation to each item in the list. For example, consider a message board. You have a list of posts to display so you write a for loop that goes through each item in your list of posts. Each time in the loop you output the necessary HTML to render the post.

In order to iterate over an array, we need to know two things. First is how to access the nth item in the list. We do this by writing the variable name followed by square brackets containing the number of the item we want to access...

$items = array("ham", "mustard", "mayo");
echo $items[1];

The above code will print out "mustard". Yes, mustard, not ham. Arrays are indexed starting with 0, not 1, so the first item in the list is index 0 and the second item of the list is index 1. The third item is index 2, etc.

The other thing we need to know to write a loop for a list is how many items are in the list so that our loop will stop at the appropriate time. There is a function called "count" that does just this.

$items = array("ham", "mustard", "mayo");
echo count($items);

Count returns the actual number of items in the list. So this would output "3".

When access items in the list, it starts with 0. When you're counting the items in the list, you start with 1.

So here's how we would write a for loop using an array...

$items = array("This", "is", "a", "test", 42);
for ($i = 0; $i < count($items); $i = $i + 1)
    echo '<p>'.$items[$i].'</p>';

The example is quite nonsensical but imagine if the items in the list were actually message board posts and the code inside the loop was actually elaborate HTML casing for the posts.

The foreach Loop

There is also a shorthand way to write loops over a list if you're starting from the beginning of the list. This is called the foreach loop.

$items = array("This", "is", "a", "test", 42);
foreach ($items as $item)
    echo '<p>'.$item.'</p>';

This code has an identical result to the code above it. But it's good to know both ways since sometimes knowing the index of the item in the list is essential to what you're trying to do. Or sometimes maybe you don't want to start with the first item and iterate over each one forwards. A generic for loop gives you more options.

Associative arrays/Hash Tables/Dictionaries

The arrays we've worked with so far are indexed by a number and have a specific order. You can also create arrays that don't have a specific order and are indexed by strings. We'll see this quite a bit when we work with databases.

To declare an associative array, we do it in pretty much the same way as a regular array, except we prepend every item with a string "key" followed by "=>"...

$person = array("name" => "Blake", "age" => 112,
                "occupation" => "Birthday Clown for hire");

To access items in a hash table, it's the same as a regular array except instead of a number, you use the string key instead.

//continued from above...
echo '<p>'.$person['name'].' ('.$person['age'].') - '.$person['occupation'].'</p>';

Adding an item is pretty straightforward...
$person['hobbies'] = "Making balloon animals";

Did I mention that arrays can contain other arrays inside of them? Let's combine (almost) everything from this section of this tutorial into one big example...


$people = array(
    array("name" => "Blake", "age" => 112,
          "occupation" => "Birthday Clown for hire",
          "interests" => array("making balloon animals", "falling down")),
    array("name" => "Gary", "age" => 19,
          "occupation" => "Student",
          "interests" => array("food", "shiny things", "DND")),
    array("name" => "Andrew", "age" => 18,
          "occupation" => "Professional speed cuber",
          "interests" => array("video games", "sleeping", "complaining"))

echo '<h1>People...</h1>';

foreach ($people as $person)
    echo '<h2>'.$person['name'].'</h2>';
    echo '<blockquote>';
    echo '<p>Age: '.$person['age'].'</p>';
    echo '<p>Occupation: '.$person['occupation'].'</p>';
    echo '<p>Interests: ';
    for ($i = 0; $i < count($person['interests']); $i = $i + 1)
        if ($i > 0)
            echo ', ';
        echo $person['interests'][$i];
    echo '</p>';
    echo '</blockquote>';

This long piece of code will generate the following HTML... (I added whitespace to make the sample more readable. The real version generated by this example would have no whitespace)



    <p>Age: 112</p>
    <p>Occupation: Birthday Clown for hire</p>
    <p>Interests: making balloon animals, falling down</p>


    <p>Age: 19</p>
    <p>Occupation: Student</p>
    <p>Interests: food, shiny things, DND</p>


    <p>Age: 18</p>
    <p>Occupation: Professional speed cuber</p>
    <p>Interests: video games, sleeping, complaining</p>

Next: Using Multiple Files
Back to Tutorial Overview