Loops in PHP
⏱ 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:
Example:
2. while Loop
Executes code as long as the condition remains true.
Syntax:
Example:
3. do...while Loop
Executes the loop at least once, then checks the condition.
Syntax:
Example:
4. foreach Loop
Used specifically for arrays and objects.
Syntax:
Example (Indexed Array):
Example (Associative Array):
5. Loop Control Statements
break
Terminates the loop.
continue
Skips the current iteration and continues with the next.
6. Nested Loops
A loop inside another loop.
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.
Register Now
Share this Post
← Back to Tutorials