"I am Saqib Jahangir. A passionate vlogger, software engineer, trainer and avid traveler with a deep love for exploring the hidden gems of our beautiful planet. With a strong foundation in Application Development, Application Architecture & Database Design and Product Management, I bring over a decade of hands-on experience building secure, scalable, and resilient web applications for a diverse range of industries."


Click Above to BOOK HOTEL NOW!

Loops (for, while, foreach)

 Loops in PHP are used to execute a block of code repeatedly until a specified condition is met. They are essential for tasks like iterating through arrays, processing data, and automating repetitive actions.


For Loop

The for loop executes a block of code a specific number of times. It is commonly used when you know in advance how many times the loop should run.

Example:

<?php

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

    echo "Number: $i\n";

}

?>

Output:

Number: 1

Number: 2

Number: 3

Number: 4

Number: 5


While Loop

The while loop executes a block of code as long as a specified condition is true. It is useful when the number of iterations is not known beforehand.

Example:

<?php

$i = 1;

 

while ($i <= 5) {

    echo "Number: $i\n";

    $i++;

}

?>

Output:

Number: 1

Number: 2

Number: 3

Number: 4

Number: 5


Do-While Loop

The do-while loop is similar to while, but it guarantees that the code block is executed at least once, even if the condition is false.

Example:

<?php

$i = 6;

 

do {

    echo "Number: $i\n";

    $i++;

} while ($i <= 5);

?>

Output:

Number: 6


Foreach Loop

The foreach loop is specifically used to iterate over arrays. It provides an easy way to access each element without using a counter.

Example:

<?php

$colors = ["Red", "Green", "Blue"];

 

foreach ($colors as $color) {

    echo "Color: $color\n";

}

?>

Output:

Color: Red

Color: Green

Color: Blue


Conclusion

Loops in PHP allow you to automate repetitive tasks efficiently. Using for, while, do-while, and foreach loops, you can handle arrays, counters, and dynamic conditions to build flexible and scalable web applications.

 

Click Below to Shop Now at AMAZON

Popular Posts

Operators (Arithmetic, Comparison, Logical)

Functions (Built-in & User-defined)