PHP Tutorial LOOPs:
PHP For LOOP and While LOOP Tutorial.
In PHP loops are known as control structures and used as a method of removing iterative tasks. When i say iterative i mean you don't have to copy and paste your code many times.
Example:
<?php
echo "page hits = 1";
echo "page hits = 2";
echo "page hits = 3";
echo "page hits = 4";
?>
To alleviate this problem you can you a simple for loop or a while loop.
FOR LOOPS:
Example:
<?php
for ($i=1;$i<=4;$i++){ echo " $i ";}
echo "page hits = $i
";
}
?>
The output from this piece of code would be
page hits = 1
page hits = 2
page hits = 3
page hits = 4
As you can see clearly using loops makes our task much easier and less repetitive. Now let's look at the code.
In For loops you will notice that the first line of our code contains three conditions.
$i=1;$i<=4;$i++
Now lets look at each one
$i=1; - This is known as the initial expression, the stating point for our loop i.e start at 1.
$i<=4;- This is known as the condition test, in here we tests the current status to determine if the loop should happen or not.
$i++ - This is known as the closing expression in our loop, it updates our loop variable.
What's happening :
1. The variable $i starts with a 1 value.
2. The condition test checks if $i has a value less than or = to
3. If the value is less than or equal to 4, do the loop. If the value is false greater than 4, skip out of the loop.