linuxStat PHP Documentation
Repeated execution of PHP code
The PHP for statement provides a mechanism
to repeatedly execute
a block of PHP code.
The for statement has the following structure:
for (initialization; condition; update) {
PHP Code 1
}
initialization, condition and update are PHP code.
Together they determine how many times PHP Code 1
enclosed within braces
{ } are executed.
The PHP code interpreter first executes initialization.
Then it tests condition. If condition
is TRUE
then PHP Code 1 is executed.
If condition
is FALSE then
execution of for statement ends.
After executing PHP Code 1, the PHP interpreter repeatedly
executes the
following sequence:
update
condition
PHP Code 1
As long as condition
is TRUE execution of the above sequence
continues.
If and when condition becomes
FALSE execution of
the for statement ends.
Thus, if condition never becomes
FALSE, execution of
the for statement continues for ever.
Example 10.1:
for($i = 1; $i < 5; $i++) {
print "Marvin K. Mooney, will you please go now! <br>";
}
In the initialization part of the above for statement,
integer variable $i is assigned 1.
Then the condition $i < 5
is tested.
Since the condition is TRUE, the print
statement is executed.
Then the update $i++ is executed.
This increments $i to 2.
The condition $i < 5
is tested again. Since the condition is TRUE,
the print
statement is executed again.
Then the update $i++ is executed again.
This continues until
an update execution results in $i
becoming 5. At this point
the condition $i < 5 is FALSE
and execution of the for statement ends.
The program in Example 10.1 in an HTML document:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/transitional.dtd">
<html>
<head>
<meta http-equiv=Content-Type content="text/html; charset=us-ascii">
<title>Executed on Dell Server, Intel Processor, created on HP laptop</title>
</head>
<body bgcolor="#6B7E23" text="#FFFF00" lang=EN-US>
<?php
# Example of how for statement works.
for ($i = 1; $i < 5; $i++) {
print "Marvin K. Mooney, will you please go now! <br>";
}
?>
</body>
</html>
Click the following link to execute the above PHP code
by my server's PHP interpreter.
Try the above example Next Index