Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Loops Сoncept | Loops
Introduction to PHP
course content

Conteúdo do Curso

Introduction to PHP

Introduction to PHP

1. First Acquaintance
2. Variables and Data Types
3. Conditional Statements
4. Arrays
5. Loops

bookLoops Сoncept

A loop in PHP is a fundamental programming structure that allows us to execute a block of code repeatedly until a specific condition is met.

Loops are essential for automating repetitive tasks, iterating over data collections, or performing operations a fixed number of times. They provide a structured way to handle tasks efficiently within a program.

Suppose we have a piece of code that needs to be executed ten times. There are two ways to achieve this:

  1. Copy and paste the code ten times;
  2. Use a loop.

Consider the following example to demonstrate the first approach to solving this task.

Comparison


As shown, we have completed the task and displayed the text on the screen ten times. However, imagine if the task were to display the text a thousand or even a million times. In such cases, using a loop becomes highly efficient.

php

main

copy
123456789101112
<?php echo "Programming is interesting"; echo "Programming is interesting"; echo "Programming is interesting"; echo "Programming is interesting"; echo "Programming is interesting"; echo "Programming is interesting"; echo "Programming is interesting"; echo "Programming is interesting"; echo "Programming is interesting"; echo "Programming is interesting<"; ?>

As we can see, we have completed the task and displayed the text on the screen ten times. But what if the task is to display the text on the screen a thousand times or even a million times? In such cases, we can use a for loop:

php

main

copy
12345
<?php for ($i = 0; $i < 10; $i++) { echo "Programming is interesting"; } ?>

With just a few lines of code, we achieve the same result. The for loop in PHP executes the block of code within its curly braces ({}) a specified number of times, controlled by the loop initialization ($i = 0), condition ($i < 10), and iteration ($i++).

In the upcoming sections, we will delve into these constructs and symbols in more detail. In practice, handling loops is often simpler than it may initially appear.

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 5. Capítulo 1
some-alt