PHP Loops
PHP Loops are used to execute the same block of code again and again until a certain condition is met.
Types of Loops
- for − loops through a block of code a specified number of times.
- while — loops through a block of code until the condition is evaluated to true.
- do…while — the block of code executed once and then condition is evaluated. If the condition is true the statement is repeated as long as the specified condition is true.
- foreach − loops through a block of code for each element in an array.
for Loop
The for loop repeats a block of code until a certain condition is met. It is typically used to execute a block of code for certain number of times.
Syntax
for(initialization; condition; increment){
// Code to be executed
}
<?php
for($i=1; $i<=5; $i++){
echo $i."\n";
}
?>
1
2
3
4
5
Run : http://ideone.com/dtOyDT
while Loop
The while loop executes a block of code as long as the specified condition is true.
Syntax
while (condition is true) {
code to be executed;
}
<?php
$n = 1;
while($n <= 5) {
echo "The number is: $n \n";
$n++;
}
?>
Run : http://ideone.com/e4QXjN
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
do…while Loop
The do…while statement will execute a block of code at least once – it then will repeat the loop as long as a condition is true.
Syntax
do {
code to be executed;
}
while (condition);
<?php
$n = 6;
do {
echo "The number is: $n \n";
$n++;
} while ($n <= 5);
?>
Run : http://ideone.com/PNpXXe
The number is: 6
foreach Loop
The foreach statement is used to loop through arrays. For each pass the value of the current array element is assigned to $value and the array pointer is moved by one and in the next pass next element will be processed.
Syntax
foreach (array as value)
{
code to be executed;
}
<?php
$fruits = array("mango", "apple", "papaya", "lichi");
foreach ($fruits as $value)
{
echo "$value \n";
}
?>
Run : http://ideone.com/tvJ0dC
mango
apple
papaya
lichi
Interview Questions & Answers |
---|
No Content Found. |