PHP Basic
Introduction to PHP PHP Starting Requirements Downloading XAMPP Local Server PHP Variable Concept and Data Type PHP Coding Syntax Showing Output in PHP PHP String Concatenation Increment & Decrement in PHP PHP Logical Operator and Usage Part-1 PHP Logical Operator and Usage Part-2 PHP Comparison Operators Arithmetic and Assignment Operators PHP Switch Case Statement For loop in PHP Super Global Variable $_REQUEST and $_GET Part-1 String Length in PHP Function Declaration and UsageLoop is a system or way of doing a work in repetitive way. When a user wants to do same work without writing it again and again, then loop can be a good solution. There are three types of loop in php. They are for, while and do while. In this post we are going to discuss about for loop.
In order to write for loop it is needed to use keyword for. After for parenthesis is needed. inside parenthesis there are three sections. First is initial start, second is conditional logic and final is increment/decrement. And after that, curly brace is needed for writing the body part of for loop.
<?php
for (initial; condition; increment/decrement) {
//code
}
?>
We will now declare a variable $p. The initial value of $p is 0. For loop starts with checking initial value. If condition becomes true, then loop will execute. below is an example.
<?php
for ($p=0; $p<10>"; //
is used for printing data in different lines
}
?>
The output of this program is:
0
1
2
3
4
5
6
7
8
9
In this for loop $p is a variable. Its initial value is zero. During starting of a loop initial value is checked. After that it checks whether the condition is true or false. If the condition becomes true then loop starts, otherwise not. It goes inside loop and executes codes. After that, the value of the value $p is increased by 1 (anything can be increased/decreased here such as $p--,$p+2,$p+3,$p*$p/2 etc.) and again executes code inside for loop in same way. This process continues until the condition $p<10>becomes false. When the condition becomes false, for loop stopped.
For loop can be forcefully stopped by using break keyword. That means when it will find break keyword inside it, then for loop will be terminated. below there is an example
<?php
for ($p = 0; $p < 10>= 5) {
break;
}
echo $p . "
";
}
?>
The result of above code is
0
1
2
3
4
The program has run until if founds break. When it founds $p is 5 then if condition executes and program has been terminated. We will give a complete clear idea about break and continue in next upcoming post. Stay with us
If you think you have query... then For contacting with us use Facebook . You can also use Github