Articles → PHP → Loops In PHP
Loops In PHP
Software Requirement
- XAMPP is installed on your machine
- Any text editor like Notepad
Technical Knowledge
- Basics about PHP?
- What are arrays in PHP?
What Are Loops?
- A structure, series, or process, the end of which is connected to the beginning
- A shape produced by a curve that bends round and crosses itself
Types Of Loops
- for loop
- while loop
- foreach loop
- do..while loop
For Loop
for (initialize counter; test counter; increment counter) {
code to be executed;
}
- initialize counter → Initialize the value of the counter from which the loop begins to execute
- Test counter → Every time the code block gets executed, for loop checks if the counter reaches the specific value (specified in the test counter). If no then for loop executes the block again or else exits the loop
- Increment counter → increments the value of the counter with a specific value
for ($x=1; $x<=5; $x++) {
echo $x;
}
While Loop
while (condition){
code to be executed;
}
$x = 1;
while($x <=5)
{
echo $x;
$x++;
}
Foreach Loop
foreach ($array as $value) {
code to be executed;
}
$arr = array("A","B","C");
foreach($arr as $value)
{
echo $value;
}
Do..While Loop
do
{
code to be executed;
}while (condition);
$x = 1;
do
{
echo $x;
}while($x != 1);