Syntax for loop
for(init;condition;increment/decrement)
{
statement
}
init - initialization of your variable/counter
condition - test whether the statement is false to be able to continue execution. If true, then the loop stops.
increment/decrement - adds/subtracts a certain value
Let's say you want to display numbers from 1 to 10 using a for loop. The following is the code.
PHP Code For Loop
<?php
for ($i=1;$i<=10;$i++)
{
echo $i;
echo "<br>";
}
?>
I will explain each line of the above code. $i will serve as your loop counter, $i<=10 is your condition and $i++ is your increment. In every iteration, the condition will be checked and will return a boolean value which is either a true or false value. Once true, it will execute the code inside the loop, otherwise, it will terminate the loop. Increment is important in a loop, without it, your browser will surely crash since you created an infinite loop.
Output For Loop
That would be all. Thank you for visiting and hope this helps you. Feel free to leave a comment below for any questions. I got some other articles related to php in blog and even related to loops.
No comments:
Post a Comment