0
0
PHPprogramming~5 mins

Why loops are needed in PHP

Choose your learning style9 modes available
Introduction

Loops help us repeat actions many times without writing the same code again and again.

When you want to print numbers from 1 to 10.
When you need to process each item in a list or array.
When you want to keep asking a user for input until they give a valid answer.
When you want to repeat a task until a condition changes.
When you want to automate repetitive tasks like sending emails to many people.
Syntax
PHP
<?php
// Example of a for loop
for (initialization; condition; increment) {
    // code to repeat
}
?>

The for loop repeats code while the condition is true.

You set where to start, when to stop, and how to move to the next step.

Examples
This prints numbers 1 to 5, each on a new line.
PHP
<?php
for ($i = 1; $i <= 5; $i++) {
    echo $i . "\n";
}
?>
This goes through each color in the list and prints it.
PHP
<?php
$colors = ['red', 'green', 'blue'];
foreach ($colors as $color) {
    echo $color . "\n";
}
?>
Sample Program

This program shows how a loop repeats the print statement three times with different numbers.

PHP
<?php
// Print numbers from 1 to 3 using a loop
for ($i = 1; $i <= 3; $i++) {
    echo "Number: $i\n";
}
?>
OutputSuccess
Important Notes

Loops save time and reduce mistakes by avoiding repeated code.

Always make sure your loop has a condition that will eventually stop it.

Summary

Loops repeat actions without rewriting code.

They are useful for lists, counting, and repeated tasks.

Make sure loops have a clear stop condition.