-
Notifications
You must be signed in to change notification settings - Fork 2
PHP Loops
Loops are blocks of code that execute a specified number of times. Using loops reduces the number of lines of code.
PHP works with 4 different types of loops:
- While loop
- Do...while loop
- For loop
- Foreach loop
The while
loop continues to excecute as long as the specified condition is true.
<?php
while(condition is true)
{
execute code;
}
?>
Example:
<?php
$x = 1;
while($x <= 3)
{
echo "x=$x ";
$x++;
}
?>
Output:
x=1 x=2 x=3
In the do...while
loop the block of code is executed before the condition is checked.
<?php
do {
execute code;
} while (condition);
?>
Example:
<?php
$x= 1;
do {
echo "x=$x ";
$x++;
} while ($x < 5);
?>
Output:
x=1 x=2 x=3 x=4
The for
loop is used when the number of times the block is to be executed is known in advance.
<?php
for (variable initialisation; test condition; increment)
{
execute code;
}
?>
Example:
<?php
for ($x=1 ; $x <= 4 ; $x++)
{
echo "x= $x ";
}
?>
Output:
x=1 x=2 x=3 x=4
The foreach
loop helps in traversing through arrays.
<?php
foreach ($array as $value)
{
executable code;
}
?>
Example:
<?php
$numbers= array("One", "Two", "Three");
foreach ($numbers as $value)
{
echo "$value ";
}
?>
Output:
One Two Three
Learn to code and help nonprofits. Join our open source community in 15 seconds at http://freecodecamp.com
Follow our Medium blog
Follow Quincy on Quora
Follow us on Twitter
Like us on Facebook
And be sure to click the "Star" button in the upper right of this page.
New to Free Code Camp?
JS Concepts
JS Language Reference
- arguments
- Array.prototype.filter
- Array.prototype.indexOf
- Array.prototype.map
- Array.prototype.pop
- Array.prototype.push
- Array.prototype.shift
- Array.prototype.slice
- Array.prototype.some
- Array.prototype.toString
- Boolean
- for loop
- for..in loop
- for..of loop
- String.prototype.split
- String.prototype.toLowerCase
- String.prototype.toUpperCase
- undefined
Other Links