PHP - SPLessons

PHP For Loop

Chapter 14

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

PHP For Loop

PHP For Loop

shape Introduction

PHP For Loop is of two types:

For Loop

shape Description

PHP For Loop is used to initialize a variable, check condition and increment (or) decrement the variable. All these three functions are declared in a single statement and can be repeated as per requirement.

Flow of control for “for” loop

1)Initialization : In initialization section, the variables are declared and initialized. Initialization will be executed only once and if it satisfies it goes to condition section.

2)Condition : In condition section, the condition is checked. If true, then control enters the loop and the statements are executed.Then the control goes to increment section. But if the condition is false, the loop is terminated.

3)Increment or Decrement : Once the loop gets executed the flow of control jumps back to Increment or Decrement section. Here the value gets incremented (or) decremented and again the control goes to condition section. This section is optional.

shape Syntax

shape Example

<!DOCTYPE html>
<html>
	<body>
	<?php
		for ($x = 0; $x <= 30; $x++) {
			echo "X Value is: $x <br>";
		}
	?>
	</body>
</html>

Output:

Foreach Loop

shape Description

Using foreach loop, a block of statements can be repeated over arrays. foreach works only on arrays.

shape Syntax

There are two types of syntax

//Syntax_1
foreach ($array  as $value){
    statement;
}

//Syntax_2
foreach ($array  as $key => $value){
    statement;
}

shape Example

<!DOCTYPE html>
<html>
	<body>
	<?php $arr = array("John", "Mike", "Henry", "Albert"); 
		foreach ($arr as $key => $value) 
		{
			echo "Key: $key; 
				  Value: $value <br>";
		}

		foreach ($arr as $value) 
		{
			echo "$value ";
		}
	?>
	</body>
</html>

Output:

Summary

shape Key Points

  • For loop initializes variables, checks condition and increments/decrements. This can be used when there is sequential input/output.
  • For each loop is applicable to arrays only.