Posts Tagged ‘while loop’

When the same block of code has to be repeated over and over again, say for ‘N’ times, we can write the block of code ‘N’ times. But still we don’t want to do this (even though we are experts in ctrl-c and ctrl-v). That’s because computers are here to reduce our work right? So, we just want to make the best use of our computers.

In PHP, we have the following looping statements :

1. while : As long as the condition specified is true, execute a block of code.

while (condition) {
//code to be executed
}


<?php

//1. while loop.
echo "<strong>1. while loop.</strong><br>";
$x=0;
while ($x<=5) {
echo "\$x : $x <br>";
$x++;
}

?>

2. do… while : The condition is checked after executing the block of code once, and loops through the block of code until the specified condition is true.

do {
//code to be executed.
} while (condition);


<?php

//2. do...while loop.
echo "<br><br><strong>2. do...while loop.</strong><br>";
$x=0;
do {
echo "\$x : $x <br>";
$x++;
} while ($x==5);

?>

3. For loop : for loop can be used when you know beforehand how many times a block of code must be executed.

for (init counter; test counter; increment counter) {
//code to be executed
}


<?php

//3. for loop.
print "<br><br><strong>3. for loop.</strong><br>";
for ($x=0; $x<=5; $x++) {
echo "\$x : $x <br>";
}

?>

4. foreach loop : This loop works only on arrays. It is used to loop through each value in an array.

foreach ($array as $value) {
//code to be executed
}


<?php

//4. foreach loop.
echo "<br><br><strong>4. foreach loop.</strong><br>";
$fruits = array("apple","mango","grape","cherry");
foreach ($fruits as $value) {
echo "$value <br>";
}

?>

Advertisements