Virtual Open Schooling Online courses available at Virtual Open Schooling (VOS), for more details kindly click here!
NIOS Silver Jubilee Year
NIOS

PHP Looping

From NIOS
Jump to: navigation, search
Previous Page Home Page Next Page
ICT Applications


The while Loop

The while loop executes a block of code while a condition is true.


Syntax

while (condition)

{

code to be executed;

}


Example


The example below defines a loop that starts with i=1. The loop will continue to run as long as i is lessthan, or equal to 3. i will increase by 1 each time the loop runs:


<html><body>

<?php

$i=1;

while($i<=3)

{

echo "The number is" . $i . "<br />";

$i++;

}

?>

</body></html>


Output:

The number is 1

The number is 2

The number is 3

The do...while Statement

The do...while statement will alwaysexecute the block of code once, it will then check the condition, andrepeat the loop while the condition is true.


Syntax


do

{

code to be executed;

}

while (condition);


Example


The example below defines a loop thatstarts with i=0. It will then increment i with 1, and write someoutput. Then the condition is checked, and the loop will continue torun as long as iis less than, or equal to 3:


<html><body>

<?php

$i=1;

do

{

$i++;

echo "The number is" . $i . "<br />";

}

while ($i<=3);

?>

</body></html>


Output:

The number is 1

The number is 2

The number is 3


The for Loop

The for loop is used when we know howmany times the script should run.


Syntax


for (init; condition; increment)

{

code to be executed;

}


Example


The example below defines a loop thatstarts with i=1. The loop will continue to run as long as i is less than, or equal to 3. i will increase by 1 each time the loop runs:


<html>

<body>

<?php

for ($i=1; $i<=3;$i++)

{

echo "The number is" . $i . "<br />";

}

?>

</body>

</html>


Output:

The number is 1

The number is 2

The number is 3

The foreach Loop

The foreach loop is used to loopthrough arrays.

Syntax


foreach ($array as $value)

{

code to be executed;

}


For every loop iteration, the value ofthe current array element is assigned to $value - so on the next loopiteration, we will be looking at the next array value.


Example


The following example demonstrates aloop that will print the values of the given array:


<html>

<body>

<?php

$x=array(1,2,3);

foreach ($x as $value)

{

echo $value . "<br/>";

}

?>

</body>

</html>


Output:

1

2

3








Previous Page Home Page Next Page
ICT Applications