Loops in PHP: For, While, and Foreach

Tutorial 5 of 5

1. Introduction

This tutorial aims to help you understand and effectively use loops in PHP. Loops are essential components of programming that allow you to repeat a block of code based on certain conditions.

You will learn:
- How to write and use 'for', 'while', and 'foreach' loops in PHP.
- Understand the use-cases for each type of loop.
- Best practices when using loops.

Prerequisites:
- Basic understanding of PHP syntax and variables.
- Familiarity with conditional statements in PHP.

2. Step-by-Step Guide

For Loop

The 'for' loop is often used when you know how many times you want to iterate over a block of code.

for (init counter; test counter; increment counter){
  // code to be executed;
}
  • init counter: Initialize the loop counter value.
  • test counter: Evaluate if the loop should continue.
  • increment counter: Increase the counter value.

While Loop

The 'while' loop continues to execute a block of code as long as the specified condition is true.

while (condition){
  // code to be executed;
}
  • condition: The loop continues as long as this condition is true.

Foreach Loop

The 'foreach' loop is used to loop through each value in an array.

foreach ($array as $value){
  // code to be executed;
}
  • $array: The array through which we're looping.
  • $value: The current value in the current iteration.

3. Code Examples

For Loop Example

for ($i = 0; $i < 5; $i++){
  echo $i;
}

This loop starts with $i = 0 and continues until $i is less than 5, incrementing $i by 1 each time. It will print numbers 0 through 4.

While Loop Example

$i = 0;
while ($i < 5){
  echo $i;
  $i++;
}

This loop will print numbers 0 through 4, same as the for loop example above. The difference is that $i is incremented within the loop body.

Foreach Loop Example

$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value){
  echo $value . "<br>";
}

This loop will iterate through each value in the $colors array and print it. So it will print "red", "green", "blue", "yellow" each on a new line.

4. Summary

  • Loops are used to execute blocks of code multiple times.
  • 'for' loops are useful when you know how many times you want to loop.
  • 'while' loops are useful when you want to loop based on a condition.
  • 'foreach' loops are used to iterate through arrays.

5. Practice Exercises

  1. Exercise Write a 'for' loop that prints the numbers 0 to 10.
    Solution
for ($i = 0; $i <= 10; $i++){
  echo $i;
}
  1. Exercise Write a 'while' loop that prints the numbers 0 to 10.
    Solution
$i = 0;
while ($i <= 10){
  echo $i;
  $i++;
}
  1. Exercise Write a 'foreach' loop that prints each value in the array array("PHP","Python","JavaScript","Ruby").
    Solution
$languages = array("PHP","Python","JavaScript","Ruby");

foreach ($languages as $value){
  echo $value . "<br>";
}

Remember to practice these concepts regularly to get comfortable with them. Happy coding!