Sometimes in your programming, you will need to repeat certain operations more than once. In this section we will look at how to use for loops to control these repeating operations.
Here is a sample of a for loop:
for ($i = 0; $i < 10; $i++)
{
(statement);
(statement);
}
Now let's talk about some of the syntax requirements of a for loop:
$i = 0;does this initializing.
$i < 10;sets this loop's condition. In this example, as long as $i is less than 10 the loop will continue.
$i++increments the variable $i by 1 each time the loop iterates. The symbol ++ is called an increment operator.
This Simple for Loop page demonstrates the basics of using a for loop.
The code for the Simple for Loop page is shown below. This is file simpleFor.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link type="text/css" rel="stylesheet" href="PHPstyles.css">
<title>A Simple for Loop</title>
</head>
<body>
<div id="mainDiv">
<h1>A Simple for Loop</h1>
<?php
for ($i = 0; $i < 10; $i++){
print "$i <br />\n";
} // end for loop
?>
</div>
</body>
</html>
Please note these points about the above code:
$i = $i + 1but is usually written with the shorthand increment operator.
You can count by values other than 1 in a for loop.
The Counting by Fives page demonstrates how to count by five in a for loop.
The code for the Count by Fives page is shown below. This is file countByFive.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link type="text/css" rel="stylesheet" href="PHPstyles.css">
<title>Counting By Fives</title>
</head>
<body>
<div id="mainDiv">
<h1>Counting By Fives</h1>
<p>
<?php
for ($i = 5; $i <= 50; $i += 5){
print "$i <br />\n";
} // end for loop
?>
</p>
</div>
</body>
</html>
Please note these points about the above code:
$i += 5uses another shortcut operator, +=. This code is equivalent to
$i = $i + 5
You can even count backwards in a for loop.
The Counting Backwards page demonstrates how to count backwards in a for loop.
The code for the Counting Backwards page is shown below. This is file countingBackwards.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link type="text/css" rel="stylesheet" href="PHPstyles.css">
<title>Counting Backwards</title>
</head>
<body>
<div id="mainDiv">
<h1>Counting Backwards</h1>
<?php
for ($i = 10; $i > 0; $i--){
print "$i <br />\n";
} // end for loop
?>
</div>
</body>
</html>
Please note these points about the above code:
$i--uses another shortcut operator, --. This code is equivalent to
$i = $i - 1
There are other types of shortcut operators in PHP. The following table shows some shortcut operators that you can use:
| Operator | Description |
|---|---|
| ++ | Increment (add 1) |
| -- | Decrement (subtract 1) |
| += | Add and Assign |
| -= | Subtract and Assign |
| *= | Multiply and Assign |
| /= | Divide and Assign |
| .= | Concatenate and Assign |
There is another kind of loop in PHP, which is more flexible than the for loop. This loop is a while loop.
Here is a sample of a while loop:
$i = 0;
while ($i < 10)
{
(statement);
(statement);
($i++);
}
Now let's talk about some of the syntax requirements of a while loop:
The Repeating Code with a while Loop page demonstrates how to use a while loop.
The code for the Repeating Code with a while Loop page is shown below. This is file while3a.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link type="text/css" rel="stylesheet" href="PHPstyles.css">
<title>Another Simple while Loop</title>
</head>
<body>
<div id="mainDiv">
<h1>A Simple while Loop 3</h1>
<form method="post" action="while3b.php">
Please type your name:
<input type="text" name="theName">
<br />
<input type="submit" value="Go">
</form>
</div>
</body>
</html>
The action page is file while3b.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link type="text/css" rel="stylesheet" href="PHPstyles.css">
<title>Another Simple while Loop</title>
</head>
<body>
<div id="mainDiv">
<h1>A Simple while Loop 3</h1>
<?php
if ((!isset($_POST["theName"])) || ($_POST["theName"] == ""))
{
echo "<a href='while3a.php'>Go back and enter your name...</a>";
}
else
{
$name2 = $_POST["theName"];
echo "The letters in $name2 are:<br />\n";
while ($name2 != "")
{
$singleChar = substr($name2,0,1);
echo "$singleChar<br />\n";
$name2 = substr($name2,1);
}
}
?>
</div>
</body>
</html>
Please note these points about the above while-loop pages:
if ((!isset($_POST["theName"])) || ($_POST["theName"] == ""))and here are some notes about this statement:
<input type="text" name="theName">
substr($name2,0,1)the 0 (zero) tells substr() to start with the first character in the string, and the 1 (one) tells substr() to extract only one character. (We will see more about string positions later in this handout, but for now, note that the first character position in PHP is at location 0 (zero).)
do while loops are very similar to while loops, except that the condition is checked at the end of each iteration (looping) instead of at the beginning.
The main difference from regular while loops is that the first iteration of a do while loop is guaranteed to run (since the condition is only checked at the end of the iteration).
Here is a sample of a do while loop:
$i = 0;
do
{
(statement);
(statement);
($i++);
}
while ($i < 10);
Now let's talk about some of the syntax requirements of a do while loop:
The Repeating Code with a do while Loop page demonstrates how to use a do-while loop.
The code for the Repeating Code with a do while Loop page is shown below. This is file do_while.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link type="text/css" rel="stylesheet" href="PHPstyles.css">
<title>A Simple while Loop</title>
</head>
<body>
<div id="mainDiv">
<h1>A Simple do while Loop</h1>
<?php
$i = 0;
do
{
print "$i <br />\n";
$i++;
}
while ($i < 10);
?>
</div>
</body>
</html>
Now you know something about various ways of making your PHP code run in loops.
So now it is time to show you arrays, which by design work very well with loops.
Arrays are special variables that are made to hold lists of information.
You can create an array in PHP simply by naming/creating a variable and putting an optional number in square brackets after the variable name. Here is an example:
$teams[0] = "Cowboys"; $teams[1] = "Giants"; $teams[2] = "Eagles"; $teams[3] = "Redskins";
You can also leave the square brackets empty. PHP will automatically supply the next number in the sequence as the index. Here is an example:
$teams[] = "Cardinals"; $teams[] = "Seahawks"; $teams[] = "Chargers";
You can also use the array( ) built-in function to make an array. Here is an example:
$binary = array("000", "001", "010", "011");
Here is a very important point: The first index in a PHP array is 0 (zero), not 1. This is how most computer languages index their arrays.
Now here is a sample page, the Basic Array page, which demonstrates two arrays.
The code for the Basic Array page is shown below. This is file basicArray.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link type="text/css" rel="stylesheet" href="PHPstyles.css">
<title>Basic Array</title>
</head>
<body>
<div id="mainDiv">
<h1>Basic Arrays</h1>
<?php
//Simply assign values to an array
$teams[0] = "Cowboys";
$teams[1] = "Giants";
$teams[2] = "Eagles";
$teams[3] = "Redskins";
$teams[] = "Cardinals";
$teams[] = "Seahawks";
$teams[] = "Chargers";
//output array values
print "<h3>Some NFL Teams</h3>\n";
for ($i = 0; $i < 6; $i++){
$realNum = $i + 1;
print "$realNum: $teams[$i]<br>\n";
} // end for loop
//Use the array() function to make an array
$binary = array("000", "001", "010", "011");
print "<h3>Binary numbers</h3>\n";
for ($i = 0; $i < count($binary); $i++){
print "$i: $binary[$i]<br>\n";
} // end for loop
?>
</div>
</body>
</html>
Please note these points about the above code:
The Fancy Old Man page demonstrates some of the power of using arrays.
The code for the Fancy Old Man page is shown below. This is file FancyOldMan.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link type="text/css" rel="stylesheet" href="PHPstyles.css">
<title>Fancy Old Man</title>
</head>
<body>
<div id="mainDiv">
<h1>Fancy Old Man (with Arrays)</h1>
<pre>
<?php
$place = array(
"on my thumb",
"on my shoe",
"on my knee",
"on my door");
//print out song
for ($verse = 0; $verse < count($place); $verse++)
{
$versenum = $verse + 1;
print <<<HERE
This old man, He played $versenum
He played knick-knack $place[$verse]
...with a knick, knack, paddy-whack
give a dog a bone
This old man came rolling home
HERE;
} // end for loop
?>
</pre>
</div>
</body>
</html>
Please note these points about the above code:
Sometimes you need to display images in a Web page in a situation where an array and a loop of some kind would be very handy.
It is not efficient to store the image files themselves in an array. But it is efficient to store the names of the image files in an array. You can even store just a portion of the file names if you want to save a little bit of memory storage on the server.
Here is an example of storing image file names in an array, and using the array to display the images in the page.
And now here is the code for this page. This is file imageArray.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link type="text/css" rel="stylesheet" href="PHPstyles.css">
<title>An Array of Images</title>
</head>
<body>
<div id="mainDiv">
<h3>Some Springtime Images</h3>
<?php
$imageArray = array("SpringFlowersPink_th","AlleySpring_th",
"AlleySpringMill_th","buds2_th");
for ($i = 0; $i < count($imageArray); $i++)
{
$fileName = "images/" . $imageArray[$i] . ".jpg";
print "<img src='$fileName' width='140' height='105' alt='Spring Images' />\n";
print " \n";
}
?>
</div>
</body>
</html>
Please note these points about the above code:
Sometimes you need to refer to the elements in an array in some other order than lowest to highest index. One way to use a different order is to store the indexes in another array, and then use a normal for loop on this additional array to get the indexes into the first array.
It gets even more interesting if you need to refer to the first array in random index order.
Here is a page which shows how to use an additional array to store indexes into the first array. The indexes will be in random order.
Here is the code: This is page indirectIndex.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link type="text/css" rel="stylesheet" href="PHPstyles.css">
<title>Indirect Array Indexes</title>
</head>
<body>
<div id="mainDiv">
<h3>Some random images:</h3>
<?php
$indexArray = array(0,0,0,0,0);
$imageArray = array("SpringFlowersPink_th","AlleySpring_th",
"AlleySpringMill_th","buds2_th");
// Make an array of indexes:
for ($i = 0; $i < count($indexArray); $i++)
{
$indexNumber = rand(0,count($imageArray)-1);
$indexArray[$i] = $indexNumber;
}
// Display the images in the order of the indexes in the $indexArray:
for ($i = 0; $i < count($indexArray); $i++)
{
$imageIndex = $indexArray[$i];
$imageName = "images/" . $imageArray[$imageIndex] . ".jpg";
print "<img src='$imageName' width='140' height='105' alt='Spring Images' />\n";
print " \n";
}
?>
<h3>(Refresh the page for a new set of images.)</h3>
</div>
</body>
</html>
Please note these points about the above code: