For Loop

Introduction
A for loop is a control structure used in programming to repeat a block of code a specific number of times. It is commonly used when the number of repetitions is known in advance. In PHP and many other programming languages, the for loop helps developers write efficient and clean code.

How For Loop Works
A for loop works by repeating a set of instructions until a condition becomes false. It consists of three main parts: initialization, condition, and increment or decrement. These parts work together to control how many times the loop will run.

Syntax of For Loop
for (initialization; condition; increment)
statement block

Example Explanation
First, the initialization sets the starting point. Second, the condition checks whether the loop should continue. Third, the increment updates the value after each iteration.

PHP For Loop Example
PHP for loop example structure is
php
for ($i = 1; $i <= 5; $i++)
echo $i

This example will display numbers from 1 to 5 by repeating the code five times.

Benefits of Using For Loop
It reduces repetitive code
It improves code readability
It saves development time
It is useful for working with arrays and data sets
It is essential for automation tasks in programming

Common Uses of For Loop
Displaying numbers in sequence
Processing arrays and lists
Generating repeated HTML elements
Running calculations multiple times
Handling database records in loops

Practice Exercise
Try creating a for loop that prints numbers from 1 to 10. Then modify it to print only even numbers.

Home Ā» PHP Fundamentals (Beginner Level) > Loops > for Loop