Lesson Weekend

Let's keep working with our grocery list from last lesson. What if we want to print out all the groceries we need in the browser, in a readable way? Create a file in your document root called array_practice.php and type this into it:

<?php
    $groceries = array("eggs", "milk", "bread");
?>
<!DOCTYPE html>
<html>
<head>
    <title>Array Practice</title>
</head>
<body>
    <h1>My Grocery List</h1>
    <h3><?php echo $groceries[0]; ?></h3>
    <h3><?php echo $groceries[1]; ?></h3>
    <h3><?php echo $groceries[2]; ?></h3>
</body>
</html>

If we open this in the browser, we can see each of the groceries displayed, but what if we had 100 different groceries to buy? We wouldn't want to write $groceries[ ] over and over again that many times. And even worse, what if we thought there were 100 groceries, but actually we need 108? We would miss those last 8 items with no errors to warn us!

Wouldn't it be great if you could just tell the PHP interpreter to take each thing in the list and print it, without having to write out the index for each item? Well, it's your lucky day! We can use two new keywords called foreach and as to print our groceries. Change your array_practice.php file to look like this:

<?php 
    $groceries = array("eggs", "milk", "bread");
?>
<!DOCTYPE html>
<html>
<head>
    <title>Array Practice</title>
</head>
<body>
    <h1>My Grocery List</h1>
    <ul>
        <?php 
            foreach ($groceries as $purchase) {
                echo "<li>" . $purchase . "</li>";
            }
        ?>
    </ul>
</body>
</html>

Let's break this down step by step.

  1. Create the basic grocery list array first.
  2. Inside of a set of <ul> tags in the body, we add <?php ?> tags so that we can use PHP code to print out each item in $groceries .
  3. Run a foreach loop on $groceries. This can be read as "For each thing in $groceries, name it $purchase, and run the code inside the curly brackets once for each $purchase.
  4. In the curly brackets, we can use $purchase as just another variable. We use echo to print it the browser, adding <li> tags around each word with the . operator. (This way we get "
  5. eggs
  6. milk
  7. bread
  8. " instead of "eggsmilkbread".

Now, we can easily print out as long a grocery list as we like! Change the first line of your php code to this:

<?php
    $groceries = array("eggs", "milk", "bread", "apples", "bananas", "fruit rollups", "steak", "kale", "pasta", "flour", "sugar", "vanilla");
?>

Now refresh your browser. You should see all your other groceries appear on the page!

Enough about groceries - let's do another couple examples in the PHP shell:

> $rainbow = array("red", "orange", "yellow", "green", "blue", "violet");
> foreach ($rainbow as $color) {
    echo $color . " ";
}

First, we create an array which holds 6 strings - one for each color in the rainbow. Then we tell the PHP interpreter to "for each thing in the $rainbow, take one at a time, refer to it as $color, and then print it out."

We could also use a foreach loop to find the total price of 5 books we are buying, whose prices are stored in an array. Type this into the PHP shell:

> $book_prices = array(25, 10.99, 13.50, 33, 50);
> $total_price = 0;
> foreach ($book_prices as $current_book_price) {
    echo "The total price so far is: $total_price";
    $total_price = $total_price + $current_book_price;
}
> echo "Our books will cost $total_price.";
The total price so far is: 0
The total price so far is: 25
The total price so far is: 35.99
The total price so far is: 49.49
The total price so far is: 82.49
Our books will cost $132.49.

We start by setting the variable $total_price to 0. Then we loop through our array of book prices, putting each value into the variable $current_book_price. Then each time through the loop we first print out the current value of $total_price, then set $total_price equal to itself plus the $current_book_price. So, at the end of the loop, $total_price holds the total of our prices, and we can see it grow each time the loop runs. $total_price starts at 0, then we add 25, then 10.99 etc.

Let's touch on one more point before we end this lesson. Why did we start by setting $total_price equal to 0? Well, if we leave that line out, the PHP interpreter will give us an error that says Notice: Undefined variable when we try to add $total_price to itself the first time. If you're adding two numbers, or two strings together, or doing anything with variables, then they need to have a value assigned to them at some point first. Even if you don't know what that value is when the variable is being used, you need to know that it has one - even if that value is a 0, or empty string (which is just two quotes with nothing between them ""), otherwise the PHP interpreter gets confused.

Now let's recap our arrays and loops, shall we?

  1. An array is a list of things, of any type. They can be created by setting the output of the array function to a variable: $pets = array("cat", "dog", "parakeet", "hedgehog");
  2. You can add new things to an array using the function array_push. For example, this adds a parrot to our array of pets: array_push($pets, "parrot");
  3. You can get individual items out of a list using the index number in square brackets. The index number is essentially the item's place in line. The first item in an array has index number 0, the second is index 1, etc. To get "dog" out of $pets we say $pets[1].
  4. You can manipulate items in an array as a group using a foreach loop. It tells the PHP interpreter to take each thing in your array, put it in a variable, and then run some code using that variable. It looks like:
foreach ($list as $item) { 
    // do things with $item 
}