
Keep Things Going with Loops and Arrays
Loops and arrays in PHP allow you to repeat your code and create or use lists of data. Arrays are a data structure that allows you to store a collection of related data. This tutorial is aimed at giving you a better understanding of how to use them. In it we will look at arrays and looping, show you some examples in the form of code snippets, and then provide an explanation of what’s happening.
There are 4 types of loops in PHP: while, do-while, for, and foreach.
PHP Arrays
An array allows you to create a collection of related items. In this example we will initialize and array of colors. In this sample we define an array of colors and print out a random color.
<?php $colors = array("red", "yellow", "blue", "white", "black", "grey", "orange", "green", "purple", "brown"); $key = rand(0,count($colors)-1); echo $colors[$key]; ?>
In this case we set the array with the array() function for PHP. The items in the array are listed as arguments for the function.
In the next line, we pick a random key for the array with the rand() function. The first argument is the lower number, and the second argument is the higher number. Array indexes start at 0 rather than 1, while counting starts at 1. We compensate for that by subtracting 1 from the count of array elements.
Finally, we print the value at our random index with the echo command.
While Loop in PHP
A while loop will execute when the condition is true. Here we use a while loop to print out all the colors in our array.
<?php $colors = ["red", "yellow", "blue", "white", "black", "grey", "orange", "green", "purple", "brown"]; while(count($colors) > 0) { echo array_pop($colors) . "<br>"; } ?>
We use the count() function in this example. In this case the loop will execute as long as there are elements in teh array.
The array_pop() function will remove and return the last element in the array. Each time we use array_pop() the array shrinks by one. Once all the elements have been removed the count reaches 0 and the condition becomes false and the loop quits executing.
Do While Loop in PHP
The do-while loop works like the while loop except that the test condition comes at the end of the loop. This ensures the loop will execute at least once.
<?php $x = 1; $numbers = array(); do { echo array_push($numbers, $x); $x++; } while ($x <= 10); print_r($numbers); ?>
In the last example we used array_pop() to remove elements from an array. In this example we use array_push() to add elements. The elements pushed onto the end of an array.
Once the loop pushes the numbers 1-10 into our array we print it out. This time we use “print_r” instead of echo. Echo only works with strings. It cannot extract the elements from an array. The print_r function will display the contents of an array (along with the keys).
For Loop in PHP
A for loop will execute a fixed number of times. In this example we will find the total of five prices in an array.
<?php $prices = [4.95, 59.99, 9.99, 99.95, 3.45]; $total = 0; for ($i = 0; $i < 5; $i++) { $total = $total + $prices[$i]; } echo "Your total is: $" . $total ?>
This array contains numbers instead of strings so we do not put the elements inside quotes.
In order to use the total outside of our loop, we need to initialize it before the loop. We do this by setting it to zero.
For each time through the loop we add one element of the array to the total.
Once the loop is done, we print out the total.
ForEach Loop in PHP
In this example the foreach loop prints a list of links for each of the titles in our array. You can add more titles, or delete some without needing to count or change the code for your loop.
Save this example as “books.php” – or change books.php in the code to the name of your file.
<?php $key=0; if(isset($_GET["key"])) { $key=$_GET["key"]; } $titles = array("Where the Red Fern Grows", "Tom Sawyer", "Pride and Prejudice", "Alice in Wonderland", "The Good Earth", "Oliver Twist", "War and Peace"); echo "<h1>$titles[$key]</h1>"; foreach ($titles as $key => $title) { echo "<a href='books.php?key=$key'>$title</a><br>"; } ?>
There are two ways to submit forms – if you use “GET” as your method then the variables are added to the filename as a visible part of the URL. That allows you to bookmark the variation and link to it. This may look familiar if you have used blogging software. We are taking advantage of that to create links that will use the book title as our page headline. To test it, click on the links. You should see the page title change to match the one you selected.
We begin by setting the key to zero in case there is no link clicked. Then we see if there is a key included in the URL. If there is, we update out key to the number indicated.
Next we have our array of book titles. Then we print the element at the indicated key as the title of our web page. When the loop ends we will have a list of all the book titles linked so that they change your page title when you click on them.
We will use this code again to link to our blog titles in the following example.
Extending the Blog Example
In this example we will modify the blog example from the “Hello, World” tutorial to include an array so that we can save more than one page.
<?php // (1) we use a session to store our arrays, if there are no arrays they are created session_start(); if(!isset($_SESSION["titles"])) { $_SESSION["titles"] = []; } if(!isset($_SESSION["contents"])) { $_SESSION["contents"] = []; } // (2) if the form was submitted we push the new entry into our arrays if($_SERVER["REQUEST_METHOD"]=="POST") { array_push($_SESSION["titles"],$_POST["title"]); } if($_SERVER["REQUEST_METHOD"]=="POST") { array_push($_SESSION["contents"],$_POST["body"]); } // (3) create default values for our first view $current_key=0; $current_title="New Blog - No Posts"; $current_body=""; // (4) check for a GET to see if we are trying to view an existing post if(isset($_GET["key"])) { $current_key = $_GET["key"]; $current_title = $_SESSION["titles"][$current_key]; $current_body = $_SESSION["contents"][$current_key]; } // (5) print out the webpage echo "<!DOCTYPE html> <html lang='en' dir='ltr'> <head> <meta charset='utf-8'> <title>$current_title</title> </head> <body> <h1>$current_title</h1> <p>$current_body</p>"; foreach ($_SESSION["titles"] as $key => $title) { echo "<a href='blog.php?key=$key'>$title</a><br>"; } echo "<div style='text-align:center;'> <form action='blog.php' method='post'> <input type='text' name='title' value='New Post Title' style='width:650px;'><br> <textarea name='body' rows='8' cols='80' placeholder='enter new post here'> </textarea> <br><input type='submit'> </form> </div> </body> </html>"; ?>
- In order to save our posts (at least until you close your browser) we will store the blog post information as session variables.
- We then check to see if our form was submitted. If we have POST information then we add the blog details to our arrays in the session variables with the array_push() function.
- We initialize our page variables for the first time the page loads.
- Next we check the URL for any GET information. If we find a key value, then we over ride the page variables with the values for that post from our array.
- Finally, we print out the web page. This is the same page used in our “Hello, World” example with the addition of the list of post links.