Loops

Contact Us or call 1-877-932-8228
Loops

Loops

As the name implies, loops are used to loop (or iterate) over code blocks. The following section shows the syntax for different types of loops. Each loop will return "12345".

There are several types of loops in PHP.

  • while
  • do...while
  • for
  • foreach

    foreach loops will be covered in the Arrays lesson.

while

while loops are used to execute a block of code repeatedly while one or more conditions is true.

Syntax

$a=1;
while ($a < 6)
{
	echo $a;
	$a++;
}

do...while

do...while loops are used to execute a block of code repeatedly until one or more conditions is found to be false. The difference between while loops and do...while loops is that the condition is checked after the code block is executed. This means that, in a do...while loop, the code block will always be executed at least once.

Syntax

$a=1;
do
{
	echo $a;
	$a++;
}
while ($a < 6);

for

A for loop takes three expressions separated by semi-colons and grouped in parentheses before the block to be iterated through.

  1. The first expression is executed once before the loop starts. It is usually used to initialize the conditions.
  2. The second expression is evaluated before each iteration through the loop. If it evaluates to false, the loop ends.
  3. The third expression is executed at the end of each iteration through the loop. It is usually used to make changes that can affect the second expression.

Syntax

for ($a=1; $a < 6; $a++)
{
	echo $a;
}

break and continue

To break out of a loop, insert a break statement.

Syntax

for ($a=1; $a < 6; $a++)
{
	echo $a;
	if ($a > 3)
	{
		break;
	}
}

To jump to the next iteration of a loop without executing the remaining statements in the block, insert a continue statement.

Syntax

for ($a=1; $a < 6; $a++)
{
	if ($a == 3)
	{
		continue;
	}
	echo $a;
}
Next