PHP Loops

PHP loops are used to loop through a block of code a specific number of times.

General Syntax

      for(initialization; condition; increment/decrement){  
//Block of code to  be executed  
}
    
Try it now

Source Code

          for ($i=1; $i<=5; $i++){  	
echo "The Number is : ".$i."<br />";	
}
        
Try it now

Let us describe every term of for loop.

  • initialization: It is used to set the initial value of the variable.
  • Condition:It checks the condition and if the condition is true then the loop execution will be continue, otherwise the execution of loop will be end.
  • Increment/decrement: It is used to increase or decrease the value of variable.

PHP forEach Loop

In PHP, each loop is used to traverse the array elements.

General Syntax

    
  foreach ($array as $key => $value) {
	// block of code to be executed
  }
   

Here,$array denotes the array variable that contains the array element and $key specifies to array element keys and $value denotes the array value with respect to $key.

Source Code

          $fruits = ['Apple', 'Banana', 'Orange', 'Mango'];
// foreach loop
foreach ($fruits as $fruit) {
	echo $fruit . '<br>';
}
        
Try it now

Note: In indexed arrays, => $value part is omitted in foreach loop.

PHP foreach With Associative Array

Source Code

          <?php
$fruits = [
	'mango' => 200,
	'orange' => 245,
	'garpes' => 130
];
foreach ($fruits as $fruit => $cost) {
	echo " $fruit, having cost: " .$cost '<br>';	
}
?>
        
Try it now

Web Tutorials

PHP Loops
Html Tutorial HTML
Javascript Tutorial JAVASCRIPT
Css Tutorial CSS
Bootstrap 5 Tutorial BOOTSTRAP 5
Bootstrap 4 Tutorial BOOTSTRAP 4