PHP For Loop


php PHP For Loop PHP Course

For Loop and its execution in PHP

Basically, for loop executes the statement for the specified number of time. We use the For Loop where we know in advance that how many times we want to execute the statement. Below example will help us to make our clear concept regarding For Loop.

For Loop Syntax:

In the above statement variable $num with the starting point that is ' 0 ' and ending point ' 5 ' and the $num++ is the increment by value 1. As starting point is 0 and Ending point is 5 and the gap between 0-5 is 6 . Hence the statement will run 6 times.

PHP program to repeat a sentence for 6 time

Repeat the statement " The quick brown fox jumps over the lazy dog." 6 times.

<?php for( $num=0 ; $num<=5; $num++ ) { echo "The quick brown fox jumps over the lazy dog"."<br>"; } ?> Output: The quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog

Print the number up to 10 using For Loop

<?php for( $num=1 ; $num<=10; $num++ ) { echo $num."<br>"; } ?>Output: 1 2 3 4 5 6 7 8 9 10

Note . In above code " <br> " is concatenated to include the line break.

Insert first 5 multiples of 2 into an array using For Loop

<?php $multiple_of_two = array(); for( $num=1 ; $num<=5; $num++ ) { $multiple = $num ✱ 2; $multiple_of_two[$num] = $multiple; } ?>

Code Explanation:

For the first cycle of For Loop $num = 1 Hence the program will work as below for the first phase.

$multiple = 1 ✱ 2; $multiple_of_two[1] = $multiple; // equal to 2

As $multiple = 2 , hence at index 1 $multiple_of_two[1] , the value ' 2 ' will store . Similarly for 5 times execution the $num variable will change and multiple will calculate and will insert into the array multiple_of_two by the index coming from variable $num.

In the Next Chapter we will perform fetching operation on array using for loop.
php PHP Course Chapter Next »