PHP / PHP Basics

Loops in PHP: For, While, and Foreach

This tutorial focuses on loops in PHP, including 'for', 'while', and 'foreach'. We’ll learn how to use these looping structures to execute blocks of code multiple times, based on …

Tutorial 5 of 5 5 resources in this section

Section overview

5 resources

Introduces the fundamentals of PHP, including syntax, variables, and basic control structures.

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!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Unit Converter

Convert between different measurement units.

Use tool

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

Countdown Timer Generator

Create customizable countdown timers for websites.

Use tool

Interest/EMI Calculator

Calculate interest and EMI for loans and investments.

Use tool

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help