For Loops


 

For Loops

For loop is used to run the code in the block in the specified number of times. It is pre-directed and can write using parameters.

For loop is used to run the code in the block in the specified number of times. It is pre-directed and can write using parameters.

For loop is used to run the code in the block in the specified number of times. It is pre-directed and can write using parameters. 

Syntax
for (init; condition; increment)
  {
  code to be executed;
  }

Parameters:

  • init: used for setting a counter (but can be any code to be executed once at the beginning of the loop)
  • condition: Evaluate for each loop iteration. If it evaluates to TRUE, the loop continues, if FALSE, the loop ends.
  • increment: used for incrementing a counter (but can be any code to be executed at the end of the loop)

The above parameters can be empty, or have multiple expressions (separated by commas).

Example

Let’s define the value of i=1 and increase it with 1. The loop begins with 1 and continues till it reaches to 5 or less then 5.

<html>
<body>

<?php
for ($i=1; $i<=5; $i++)
  {
  echo “The number is “ . $i . “<br />”;
  }
?>

</body>
</html>

Output:

The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

3.10.4. Foreach Loop

This loop is basically developed for running the block of code in the arrays.
Syntax
foreach ($array as $value)
  {
  code to be executed;
  }

For every loop iteration, the value of the current array element is assigned to $value (and the array pointer is moved by one). So on the next loop iteration, you'll be looking at the next array value.

Example

The following example demonstrates a loop that will print the values of the given array:
<html>
<body>

<?php
$x=array(“one”,“two”,“three”);
foreach ($x as $value)
  {
  echo $value . “<br />”;
  }
?>

</body>
</html>

Output:
one
two
three

Ads