Repetitive commands in php (for – while – do / while)

Repetitive comands in php are similar to the C language.

Structure for:
for ([Initialization of the variable]; [Condition]; [Increase or decrease of the variable])
{
[Instructions];
}

The first example we will do is show on the page the numbers from 1 to 100:

html>
<head>
<title> Problem </title>
</head>
<body>
<? php
for ($f = 1; $f <= 100; $f ++)
{
echo $f;
echo “<br>”;
}
?>
</body>
</html>

Who has not seen the for structure in another language we will explain it:

for ($f = 1; $f <= 100; $f ++)
{
echo $f;
echo “<br>”;
}

The first argument of the for is the initialization of a variable, in this case the variable $ f is initialized with the value 1. This first argument of the for is executed only once. Then the second argument is executed which is the condition. If it is verified as true, the entire block between the open and closed braces is executed. After the repetitive block has been executed, the third argument of the for is executed, which is the increment of the variable, in this case $ f ++ increases the content of the variable $ f by 1 (we can also put the allocation $ f in place of $ f ++ = $ f + 1).
After the variable is increased, the for condition (second argument) is executed again. If it is validated again true, it will execute the repetitive block.
This cycle is repeated until the for condition is verified false.

The second repetitive structure is:
while (condition)
{
[Instructions];
}

This structure is in almost all languages. The block is repeated as long as the while condition is true.
The while condition is verified before entering the block to be repeated. If it is verified false the first time, the block will not be executed.
Let’s see an example: Generate a random value between 1 and 100, then print on the page from 1 to the generated value (one by one):

<html>
<head>
<title> Problem </title>
</head>
<body>
<? php
$value = rand (1,100);
$start = 1;
while ($ start <= $ value)
{
echo $start;
echo “<br>”;
$start ++;
}
?>
</body>
</html>

The variable $start has the value 1 before entering the while. Every time the while block is executed once, $ start is increased by one. When $start exceeds the random variable $ value, the repetitive structure will end and the instruction immediately following the closing brace will be executed.
It is important to note that after the while condition we DO NOT have a POINT and COMMA.

Finally we have in the language a repetitive structure similar to the while called do / while, where the condition is verified after executing the repetitive block.
do
{
[Instructions];
} while (condition);

It remains as a task to try to make a page using this structure. Note that at the end of the while line it DOES HAVE a semicolon.

This article was written by admin

Leave a Reply