⇧
vadnica-logo
Editor My Blog Password Manager Finance My Services About the Project Telegram O meni O meni

PHP Loops

When writing code, we often want the same block of code to repeat a certain number of times. Instead of manually duplicating lines in a script, we use loops. Loops execute a block of code as long as a specified condition is true. We will explore the most common loops alongside the break and continue statements, which help us precisely control their execution. Each loop has its own advantages and is chosen based on the specific situation.

EXAMPLE
RESULT
The result will be displayed here...

Overview of Loop Types in PHP

Depending on whether we know the number of repetitions in advance or depend on a condition, we choose the appropriate tool:

  1. for: Used when we know exactly how many times the code block should repeat in advance (it contains an initializer, condition, and increment/decrement).
  2. while: Repeats code as long as a specified condition evaluates to true. It checks the condition before each execution of the block.
  3. do-while: Similar to a while loop, but it always executes the code block at least once, since the condition is checked only at the end of the block.
  4. foreach: A special and highly convenient loop designed exclusively for iterating through elements of arrays.
  5. break: A command that immediately terminates and exits the entire loop, continuing with the code directly below it.
  6. continue: A command that skips the remainder of the code in the current iteration and immediately jumps to the next step of the loop.

⚠️ Caution: Infinite Loop Danger

When working with while and do-while loops, you must always ensure that the condition inside the loop will eventually evaluate to false. If you forget to change the value (for instance, forgetting to increment the counter with $i++), the loop will never stop. This is called an infinite loop, which can heavily overload the server or freeze the web browser!