دستورات for در PHP

PHP برای اجرای بلوک کد به تعداد مشخص.

دستورات for در PHP

If you have already determined the number of times the script should run in advance, you can use the for loop.

Syntax

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

Parameters:

  • init counter: initialize the value of the loop counter
  • test counter: evaluate each iteration of the loop. If the value is TRUE, continue the loop. If its value is FALSE, the loop ends.
  • increment counter: increase the value of the loop counter

The following example shows the numbers from 0 to 10:

Example

<?php 
for ($x=0; $x<=10; $x++) {
  echo "Number is: $x <br>";
} 
?>

Run Example

PHP foreach Loop

The foreach loop is only applicable to arrays and is used to iterate over each key/value pair in the array.

Syntax

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

With each iteration of the loop, the value of the current array element is assigned to the $value variable, and the array pointer moves sequentially until it reaches the last array element.

The following example demonstrates a loop that outputs the values of the given array ($colors):

Example

<?php 
$colors = array("red","green","blue","yellow"); 
foreach ($colors as $value) {
  echo "$value <br>";
}
?>

Run Example

In the following chapters, you will learn more about arrays.