Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende For-Loops | Loops
Introduction to PHP

book
For-Loops

A for loop repeats a particular block of code multiple times. For example, if we want to check each student's grade in a class of 32 students, we loop from 1 to 32. The for loop is used to repeat a section of code a known number of times.

Some everyday examples of using a for loop:

  • Calculating the total cost of items in a shopping cart. For instance, summing up the prices of all items in a list of purchases;

  • Printing all even days in a month. For example, printing all the even days in July;

  • Iterating through a guest list for a party. For example, printing the names of all guests.

Syntax


Let's look at the syntax of the for loop using the example code below:

php
for (Initialization; Condition; Increment/Decrement) {
// code block
}

The for loop has three parts:

  • Initialization is the process of setting the initial value of the variable i to 0.

  • Condition is the condition that determines whether the loop will continue iterating, checking if i is less than 5.

  • Increment or Decrement are the operations performed on the counter at the end of each loop iteration.

php

main

copy
<?php
for ($i = 1; $i <= 5; $i++) {
echo "Iteration {$i}\n";
}
?>
12345
<?php for ($i = 1; $i <= 5; $i++) { echo "Iteration {$i}\n"; } ?>
  • for loop in PHP is used to iterate a specific number of times.

  • $i = 1; - Initializes the variable $i with a value of 1 before starting the loop.

  • $i <= 5; - Condition that is checked before each iteration. The loop continues as long as this condition is true.

  • $i++ - Increment operation that increases the value of $i by 1 after each iteration.

This code will print "Iteration 1" through "Iteration 5" because the condition $i <= 5 is true for values of $i from 1 to 5.

Tarea

Swipe to start coding

Fill in the blanks in the given code so that the message "Programming is fun!" is displayed three times. Use the variable $i as the counter for the for loop.

Solución

<?php
$message = "Programming is fun!";
$count = 3;
for ($i = 1; $i <= $count; $i++) {
echo $message . "\n";
}
?>

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 5. Capítulo 4
<?php
$message = "Programming is fun!"; // Message to output
$count = 3; // The number of times to display the message
for (___; $i <= $count; ___) {
echo $message . "\n"; // The newline symbol `\n` moves the text to the next line, like pressing Enter.
}
?>

Pregunte a AI

expand
ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

some-alt