Contact Information

KodeBlog

We're Available 24/ 7. Drop us an email.

PHP - Loop Types

We use Loops in PHP language to execute the same segment of code for a given amount of times. In order to achieve this goal PHP has an option that supports four types of loop types which are called for, while, do...while and foreach loops. In this chapter we will focus on how these loops can be implemented using PHP code.

Topics to be covered

We will cover the following topics in this lesson

  • For loop
  • While loop
  • Do...while loop
  • Foreach loop
  • Summary

For loop

For loop is used for a specific number of loops to be executed in a statement or a block of code.

In the following Syntax the initialization bit is used to set the starting value for the counter of the number of loop iterations. The variable may be declared here for this very purpose and it is orthodox to name it $i

for (initialization; condition; and then the increment) {
	code to be executed for loop;
}

For example

<?php

$foo = 0;
$bar = 0;

for($i = 0; $i < 5; $i++) {
    $foo += 10;
    $bar += 5;
}

echo ("At the end of the Loop Foo = $foo and Bar = $bar");

?>

HERE,

  • $foo = 0; $bar = 0; initializes the variables $foo and $bar to values 0.
  • for($i = 0; $i < 5; $i++) {...} starts our for loop. $i = 0 is the initializer that sets the value of the variable $i equal to 0. $i < 5; is the condition that checks if the value of $i is less than 5. $i++ increments the value of our initializer variable $i by the value 1.
  • $foo += 10; adds the value 10 to the existing value of $foo
  • $bar += 5; adds the value 5 to the existing value of $bar.
  • echo ("At the end of the Loop Foo = $foo and Bar = $bar"); prints our the values of $foo and $bar.

Above code will return the following output:

At the end of the Loop Foo = 50 and Bar = 25

In the above example the code makes 5 iterations and changes the assigned value of 2 variables (foo, and bar) on each pass of the loop

While loop

We use the While loop to execute a block of code until the testing expression is found to be false.

Once the testing expression is true(found to be true) only then the code block will be executed. After the execution of code the specific expression will again be evaluated and the loop will continue until the testing expression is found to be false.

while (condition) {
	the code for while loop is to be executed here;
}

For Example

<?php

$i = 0;
$foo = 49;

while( $i < 10) {
	$foo--;
	$i++;
}

echo ("Loop stopped at i = $i and foo = $foo" );

?>

HERE,

  • $i = 0; $foo = 49; initializes the values $i and $foo to the values 0 and 49 respectively.
  • while( $i < 10) {...} checks if the condition $i < 10 is true. If true, then the code block within the while loop will be executed. If false, the program moves on to the next statements below the while loop.
  • $foo--; decreases the value of $foo by 1.
  • $i++; increases the value of $i by 1.

This will return the following output

Loop stopped at i = 9 and foo = 49

In the above example the loop will decrease a variable value on each iteration of the loop and the counter increments until the value reaches the value of integer 9 when the evaluation is false and then the loop will end

Do...while loop

With the do...while loop we can execute a block of code at least once and then it should repeat the loop for as long as until the condition is found to be true

do {
	write code to be executed here;
}
while (condition goes here);

For example

<?php

$i = 0;
$foo = 0;

do {
	$i++;
}
while( $i < 9 );

echo ("The Loop stopped when the value of  i was at $i" );

?>

HERE,

  • $i = 0; $foo = 0; initializes the value of the variables $i and $foo to 0 and 0 respectively.
  • do {...} starts our do loop that executes the code at least once before evaluating the condition.
  • echo ("The Loop stopped when the value of i was at $i" ); outputs the value of $i at the end of the loop execution.

The above code is an example of how a do...while loop can be utilized and above code will return the following output

The Loop stopped when the value of i was at 9

In the above example there was an increment in the value of i at least once, and it continued increasing the variable i until it reached the value of 9

Foreach loop

So we use this foreach loop statement when we are in need to running the loop through arrays. Foreach pass the value of the current array element is assigned to a variable and the array pointer is moved by one and then in the next pass next element will be processed.

foreach (array as value) {
	code for the loop will be executed here;
}

 

For example

<?php

$cities = array('Dubai','London','New York','Paris','Tokyo');

foreach($cities as $city) {
    echo "The City is $city<br />";
}

?>

HERE

  • $cities = array('Dubai','London','NewYork','Paris','Tokyo'); defines an array variable $cities that contains cities
  • foreach($cities as $city) {...} loops through the array variable and assigns the value of the iteration element to the variable $city
  • echo "The City is $city<br />"; outputs the value of city at each iteration

Above code will return the following output

The City is Dubai
The City is London
The City is New York
The City is Paris
The City is Tokyo

As we can see in the above code example an array of 5 cities were coded and using foreach loop we were able to type each array as a value of variable by just using a single echo statement (i.e. . The City is $variable<br />) If it were integers instead of strings (or cities or countries for that matter or any other string) it would have ran through 1st value till the 5th value. For example

  • echoing same text but with array value of 1
  • echoing same text but with array value of 2
  • echoing same text but with array value of 3
  • echoing same text but with array value of 4
  • echoing same text but with array value of 5

(Or the counting could start from 0 as array starts from 0 but it depends on user-input of integer).

Summary

Loops are used to execute the same code a number of times usually with different parameter during each iteration. For loops are used to execute the same code a known number of times while Do loops are used to execute the same code repeatedly without knowing the number of times that it will execute in advance.

For loop is used to run same code a number of times e.g. 5 times. Foreach loop is used to iterate through array variables untill all elements in the array have been read. Do while is used to execute the same code as long as the define condition is true. Do... while execute the loop atleast once before evaluating the condition.

SUPPORT US

If you found this tutorial useful, support us by using the social media buttons to like and share the tutorial. If you didn’t find it useful, please use the comments section below to let us know how we can do better next time.

Subscribe to our newsletter, like our Facebook fan page or follow us on Twitter to get free updates when we publish new tutorials

Author: Rodrick Kazembe

Rodrick is a developer who works on Desktop, Web and Mobile Applications. He is familiar with Python, Java, JavaScript, C++, C#, Kotlin, PHP, Python and the list goes on. Rodrick enjoys sharing knowledge especially when it comes to technology.

PHP - Decision Making

PHP - GET & POST

Leave A Reply