Loops in PHP

📘 PHP 👁 31 views 📅 Dec 22, 2025
⏱ Estimated reading time: 2 min

Loops in PHP are used to execute a block of code repeatedly as long as a specified condition is met. They help reduce code duplication and make programs more efficient and readable.


1. for Loop

Used when the number of iterations is known in advance.

Syntax:

for (initialization; condition; increment/decrement) { // code to execute }

Example:

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

2. while Loop

Executes code as long as the condition remains true.

Syntax:

while (condition) { // code block }

Example:

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

3. do...while Loop

Executes the loop at least once, then checks the condition.

Syntax:

do { // code block } while (condition);

Example:

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

4. foreach Loop

Used specifically for arrays and objects.

Syntax:

foreach ($array as $value) { // code }

Example (Indexed Array):

$colors = ["Red", "Green", "Blue"]; foreach ($colors as $color) { echo $color; }

Example (Associative Array):

$user = ["name" => "John", "email" => "john@example.com"]; foreach ($user as $key => $value) { echo "$key : $value"; }

5. Loop Control Statements

break

Terminates the loop.

for ($i = 1; $i <= 10; $i++) { if ($i == 5) { break; } }

continue

Skips the current iteration and continues with the next.

for ($i = 1; $i <= 5; $i++) { if ($i == 3) { continue; } echo $i; }

6. Nested Loops

A loop inside another loop.

for ($i = 1; $i <= 3; $i++) { for ($j = 1; $j <= 3; $j++) { echo "$i $j"; } }

Conclusion

Loops in PHP are essential for working with repetitive tasks, arrays, and large datasets. Understanding for, while, do...while, and foreach loops helps you write cleaner and more efficient PHP code and prepares you for advanced programming and framework usage like Laravel.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes