PHP - Break Continue

PHP - Break Continue

Understanding Break and Continue in Loops

Introduction to Break

  • The video begins with an introduction to the break statement, which allows exiting a control structure when encountered.
  • A variable named parar is defined, which will trigger the loop to stop when it equals 20. The loop is set to iterate from 1 to 50.

Implementation of Break

  • The instructor explains that the print statement for 20 is placed before the condition check. If conte equals parar, a break command is executed.
  • Upon reaching this point, instead of returning to check conditions again, the program jumps directly out of the loop due to the break.

Observing Break in Action

  • When tested in a browser, only numbers up to 20 are printed despite setting the loop limit at 50. This demonstrates how break effectively exits loops.

Introduction to Continue

  • Transitioning into the continue statement, it's explained that unlike break, it does not exit the loop but skips directly back to its beginning.

Implementation of Continue

  • A new variable called pular is introduced; its purpose is to skip printing number 20. The print statement now occurs after checking if it should continue.
  • As each number from 1 upwards is evaluated against being equal to 4 (initially set for testing), if it matches, a continue command sends control back to the start without printing.

Infinite Loop Scenario with Continue

  • An infinite loop scenario arises as every time it checks for equality with 4 and finds true, it continues without incrementing or printing until manually stopped.

Conclusion on Control Statements