0% found this document useful (0 votes)
41 views

PHP For Loop

The document discusses PHP loops and their different types. It explains that PHP supports four loop types - for, while, do...while, and foreach. The for loop executes code a specified number of times. It provides the format for a for loop which includes a start value, end value, and update expression. The while loop executes code as long as a condition is true. The do...while loop executes code once and then repeats the loop as long as the condition is true. The foreach loop executes code for each element in an array.

Uploaded by

SIDNY BASCO
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

PHP For Loop

The document discusses PHP loops and their different types. It explains that PHP supports four loop types - for, while, do...while, and foreach. The for loop executes code a specified number of times. It provides the format for a for loop which includes a start value, end value, and update expression. The while loop executes code as long as a condition is true. The do...while loop executes code once and then repeats the loop as long as the condition is true. The foreach loop executes code for each element in an array.

Uploaded by

SIDNY BASCO
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

PHP For Loops

Loops in PHP are used to execute the same block of code a specified number of times. PHP
supports following four loop types.

✓ for - loops through a block of code a specified number of times.


✓ while - loops through a block of code if and as long as a specified condition is true.
✓ do...while - loops through a block of code once, and then repeats the loop as long as
a special condition is true.
✓ foreach - loops through a block of code for each element in an array. We will discuss
about continue and break keywords used to control the loops execution.

• A loop is something that goes round and round.


• Except a programming loop will go round and round until you tell it to stop.
• You also need to tell the program two other things - where to start your loop, and what
to do after it’s finished one lap (known as the update expression).

You can program without using loops. But it’s an awful lot easier with them. Consider this.

You want to add up the numbers 1 to 4: 1 + 2 + 3 + 4. You could do it like this:

$answer = 1 + 2 + 3 + 4;
print $answer;

• Fairly simple, you think. And not much code, either. But what if you wanted to add up
a thousand numbers? Are you really going to type them all out like that?
• It’s an awful lot of typing. A loop would make life a lot simpler. You use them when you
want to execute the same code over and over again.

For Loops

The for loop statement The for statement is used when you know how many times you want
to execute a statement or a block of statements.
Here’s a PHP For Loop in a little script. Type it into new PHP script and save your work. Run
your code and test it out.

<?PHP
$counter = 0;
$start = 1;
for($start; $start < 11; $start++) {
$counter = $counter + 1;
print $counter . "<BR>";
}
?>

The format for a For Loop is this:

for (start value; end value; update expression) {


}

The first thing you need to do is type the name of the loop you’re using, in this case for. In
between round brackets, you then type your three conditions:

Start Value

1
The first condition is where you tell PHP the initial value of your loop. In other words, start the
loop at what number? We used this:

$start = 1;

Assign a value of 1 to a variable called $start. Like all variables, you can make up your own
name. A popular name for the initial variable is the letter i. You can set the initial condition
before the loop begins, like we did:
$start = 1;
for($start; $start<11; $start++) {
Or you can assign your loop value right in the For Loop code:

for($start=1; start<11; start++) {

The result is the same – the start number for this loop is 1

End Value

Next, you have to tell PHP when to end your loop. This can be a number, a Boolean value, a
string, etc. Here, we’re telling PHP to keep going round the loop while the value of the variable
$start is Less Than 11.

for($start; $start < 11; $start++) {

When the value of $start is 11 or higher, PHP will bail out of the loop.

Update Expression

Loops need a way of getting the next number in a series. If the loop couldn’t update the starting
value, it would be stuck on the starting value. If we didn’t update our start value, our loop would
get stuck on 1. In other words, you need to tell the loop how it is to go round and round. We
used this:
$start++

In a lot of programming language (and PHP) the double plus symbol (++) means increment
(increase the value by one). It’s just a short way of saying this:

$start = $start + 1

You can go down by one (decrement) by using the double minus symbol (--), but we won’t go
into that.

So our whole loop reads “Starting at a value of 1, keep going round and round while the start
value is less than 11. Increase the starting value by one each time round the loop.”
Every time the loop goes round, the code between our two curly brackets { } gets executed:

$counter = $counter + 1;
print $counter . "<BR>";

Notice that we’re just incrementing the counter variable by 1 each time round the loop, exactly
the same as what we’re doing with the start variable. So we could have put this instead:

$counter ++

2
Example The following example makes five iterations and changes the assigned value of two
variables on each pass of the loop:

loop1.php output
<html>
<body>
<?php
$a = 0;
$b = 0;
for( $i=0; $i<5; $i++ )
{
$a += 10;
$b += 5;
}
echo ("At the end of the loop a=$a
and b=$b");
?>
</body>
</html>

Syntax

for (initialization; condition; increment)


{
code to be executed;
}

✓ The initializer is used to set the start value for the counter of the number of loop
iterations.

✓ A variable may be declared here for this purpose and it is traditional to name it $i.

3
A PHP Times Table Program

<html> A PHP Times Table Program


<head>
<title>A Times Table Program</title>

<?PHP
$times=2;

if (isset($_POST['Submit1'])) {

$start=$_POST['txtStart'];
$end=$_POST['txtEnd'];
$times=$_POST['txtTimes'];

for ($start; $start<=$end; $start++) {


$answer=$start * $times;
print $start. "multiplied by". $times. " = " . $answer. "<BR>";
}
}
?>
</head>
<body>

<FORM NAME=frmOne Method="POST" Action="timesTable.php">

Start Number: <INPUT TYPE=Text NAME=txtStart SIZE=5 value="1">


End Number: <INPUT TYPE=Text NAME=txtEnd SIZE=5 value="10">
Multiply By: <INPUT TYPE=Text NAME=txtTimes SIZE=5 value=<?PHP print
$times;?>>
<P>
<INPUT TYPE=Submit Name=Submit1 VALUE="Do Times Table">
<P>
</FORM>
</body>
<html>

Output:

Get the values from the textboxes and create a Times Table program. When the button is
clicked, the output will be something like this:

4
Code Explanation

We need all those numbers from the textboxes on the form, so we start with:

$times = 2;
if (isset($_POST['Submit1'])) {
$start = $_POST['txtStart'];
$end = $_POST['txtEnd'];
$times = $_POST['txtTimes'];
}

The first line just puts a value in the variable called $times. This is so that the "Multiply By"
textbox will have a default value when the page is loaded.

Next we use the isset( ) function again, just to check if the user clicked the Submit button.
This is exactly the same as you saw in the last section.
To get the values from the textboxes, we use the following:

$start = $_POST['txtStart'];
$end = $_POST['txtEnd'];
$times = $_POST['txtTimes'];

Again, this is code you met in the last section. You just assign the values from the textboxes
to the new variables using $_POST[]. In between the square brackets, we've typed the NAME
of the HTML textboxes. So this gives us the values that the user entered on the form. Next
comes out For Loop:

for($start; $start <= $end; $start++) {


$answer = $start * $times;
}
Let's look at that first line again:
for($start; $start <= $end; $start++) {

5
So we have a starting value for our loop, an end value, and an update expression. The starting
value is coming from the variable called $start. This will be whatever number the user entered
in the first textbox. The default is 1. Look at the end value, though:

$start<=$end

The end value is when the value in the variable called $start is less than or equal to the value
held in the variable called $end. This works because we're increasing the value of $start each
time round the loop. The variable called $end is a fixed value, and comes from the textbox on
the form.

The last part of the loop code is the update expression. This tells PHP to increase the value
of $start each time round the loop:

$start++

The double plus symbol (++) means "add 1 to the number held in $start".
And that's the essence of for loops: provide a start value, an end value, and how you want to
update each time round the loop.

The code inside the for loop, however, the code that gets executed each time round the loop,
is this:
$answer=$start * $times;

Remember, the variable $times holds the times table, the 2 times table by default. This is
being multiplied by whatever is inside the variable $start. Each time round the loop, $start will
have a different value – first 1, then 2, then 3, etc. The answer is then stored in the variable
that we called $answer. So it's really doing this:

$answer = 1 * 2;
$answer = 2 * 2;
$answer = 3 * 2;
etc

Finally, we displayed the result to the page like this:

print $start. " multiplied by ". $times. " = " . $answer. "<BR>";

PHP While Loops

• The while statement will execute a block of code if and as long as a test expression is
true. If the test expression is true, then the code block will be executed.
• After the code has executed the test expression will again be evaluated and the loop
will continue until the test expression is found to be false.
• Instead of using a for loop, you have the option to use a while loop.
• The structure of a while loop is simpler than a for loop, because you’re only evaluating
the one condition.
• The loop goes round and round while the condition is true. When the condition is false,
the program breaks out of the while loop. Here’s the syntax for a while loop:

while (condition) {
statement
}

And here’s some code to try. All it does is increment a variable called counter:
$counter = 1;

6
while ($counter < 11) {
print (" counter=".$counter ."<BR>");
$counter++;
}
• The condition to test for is $counter < 11. Each time round the while loop, that
condition is checked. If counter is less than eleven then the condition is true. When
$counter is greater than eleven then the condition is false. A while loop will stop going
round and round when a condition is false.

• If you use a while loop, be careful that you don’t create an infinite loop. You’d create
one of these if you didn’t provide a way for you condition to be evaluated as true. We
can create an infinite loop with the while loop above. All we have to do is comment out
the line where the $counter variable is incremented. Like this:

$counter = 1;
while ($counter<11) {
print (" counter = ". $counter. "<BR>");
//$counter++;
}

• Notice the two forward slashes before $counter++. This line will now be ignored.
Because the loop is going round and round while counter is less than 11, the loop will
never end – $counter will always be 1.

• Here’s a while loop that prints out the 2 times table. Try it out in a script.

$start = 1;
$times = 2;
$answer = 0;

while ($start<11) {
$answer = $start * $times;
print ($start. " times ". $times. " = " . $answer. "<BR>");
$start++;
}

PHP Do ... While loops

• The do...while statement will execute a block of code at least once - it will then repeat
the loop as long as a condition is true.
• This type is loop is almost identical to the while loop, except that the condition comes
at the end:

Syntax

do
{
code to be executed;
}
while (condition);

• The difference is that your statement gets executed at least once. In a normal while
loop, the condition could be met before your statement gets executed.

7
• Example The following example will increment the value of i at least once, and it will
continue incrementing the variable i as long as it has a value of less than 10:

loop2.php output
<html>
<body>
<?php
$i = 0;
$num = 0;
do
{
$i++;
}
while( $i < 10 );
echo("Loop stopped at i = $i" );
?>
</body>
</html>

The foreach loop statement

• The foreach statement is used to loop through arrays.


• For each pass the value of the current array element is assigned to $value and the
array pointer is moved by one and in the next pass next element will be processed.
Syntax
foreach (array as value)
{
code to be executed;
}

• Example try out the following example to list out the values of an array.

loop3.php output
output
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
echo "Value is $value <br />";
}
?>
</body>

</html>

8
The PHP break statement

• The PHP break keyword is used to terminate the execution of a loop prematurely.
• The break statement is situated inside the statement block. If gives you full control and
whenever you want to exit from the loop you can come out.
• After coming out of a loop immediate statement to the loop will be executed.
• There are times when you need to break out of a loop before the whole thing gets
executed. Or, you want to break out of the loop because of an error your user made.
• In which case, you can use the break statement. Fortunately, this involves nothing
more than typing the word break. Here’s some not very useful code that demonstrates
the use of the break statement:

$TeacherInterrupts = true;
$counter = 1;

while ($counter < 11) {


print(" counter = " + $counter + "<BR>");
if ($TeacherInterrupts == true) {
break;
}
$counter++;
}

Output:

• Example In the following example, the condition test becomes true when the counter
value reaches 3 and loop terminates.

loop4.php output

<html>
<body>
<?php
$i = 0;
while( $i < 10)
{
$i++;
if( $i == 3 )break;
}
echo ("Loop stopped at i = $i");
?>
</body>
</html>

You might also like