PHP tutorial-Loops


PHP Loops


Loops execute a block of code repeatedly while a condition is true. There are different types of loops in PHP:

for loop

The for keyword is used to construct the for loop. The inital value represents the start point of the loop. The condition can be true or false, if it is true, the for loop continues its process. Otherwise, it stops. The update represents the increase or decrease to the initial value while the condition is true. The statements to be executed will be placed in the curly braces.

for(initial value;condition;update){
  statement1;
  statement2;
}
 
Example:
<html>
<body>
 
<?php
$darr=array
(
 "set1"=>array(1,2,3),
 "set2"=>array(4,5,6)
);
 
for($i=0;$i<=2;$i++){
echo $darr["set1"][$i]."<br />";
}
 
?>
 
</body>
</html>

while loop

You will use the while keyword to construct the while loop. You can use the general form below to construct the while loop. The while loop executes when the condition is true. The statements to be executed will be placed in the curly braces as in the for loop.

initial value;
while(condition){
   statement1;
   statement2;
   update;
}
 
Example:
<html>
<body>
 
<?php
$darr=array
(
 "set1"=>array(1,2,3),
 "set2"=>array(4,5,6)
);
 
$i=0;
while($i<=2){
echo $darr["set1"][$i]."<br />";
$i++;
}
 
?>
 
</body>
</html>

do while loop

The do while loop works similarly to while loop except that do while loop executes a block of code one time when the condition is not true.

initial value;
Do
{
  statement1;
  statement2;
  increment;
}while(condition);
 

Example:
<html>
<body>
 
<?php
$darr=array
(
 "set1"=>array(1,2,3),
 "set2"=>array(4,5,6)
);
 
$i=0;
do {
echo $darr["set2"][$i]."<br />";
$i++;
}while($i<=2);
 
?>
 
</body>
</html>

foreach loop

The foreach loop uses the foreach keyword. foreach loop is used to traverse through a collection object (e.g array). By using the foreach loop to access the array elements, you do not need to specify the initial value, condition, or update. The loop will start from the first element and continue until the end of the array.


Example:
<html>
<body>
 
<?php
$darr=array
(
 "set1"=>array(1,2,3),
 "set2"=>array(4,5,6)
);
 
foreach($darr["set1"] as $value){
 echo $value."<br />";
}
 
?>
 
</body> </html>



Comments





This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.