PHP for each loop

In PHP, For each loop is one of the powerful way to achieve various result through loops. To better understand for each loop lets take one simple example.

PHP for each loop


Example:

Lets say a requirement came to print 1 to 10.

Solution:

<?php
echo "1";
echo "2";
echo "3";
echo "4";
echo "5";
echo "6";
echo "7";
echo "8";
echo "9";
echo "10";
?>
Now suppose imagine, if instead of 1 to 10, 1 to 1000 was required to print then the above approach would be very time consuming.

To handle such situation, reduce down effort and time consumption we use for loop.

Notice in the above example, starting value is 1 and end value is 10 and each time the value is incremented by 1.

Therefore when ever we want to use for loop, we must have to know in advance what is the starting value, what is the end value and how much value is incremented in each loop.

Syntax

for ( starting value; condition; increment or decrement value){
               // task
}

Lets print 1 to 10 using for loop

Here the starting value is 1.
The ending value is 10 and each time the value is incremented by 1.

Starting value: $i=1;
Condition: $i<=10;
increment or decrement value=$i++

lets put it into the for loop syntax

<?php
for($i=1;$i<=10;$i++){
echo $i;
}
?>
Output:

1
2
3
4
5
6
7
8
9
10

Try yourself.

Print 10 to 1 using for loop in reverse order.

(Try and then check following solution)

Solution:
<?php
for($i=10;$i>=1;$i--){
echo $i;
}
?>

Output:

10
9
8
7
6
5
4
3
2
1
PHP for each loop PHP for each loop Reviewed by Pixel Stream on December 10, 2019 Rating: 5

No comments:

Powered by Blogger.