Loops
Last updated
What is Loops?
PHP incorporates the use of loops, which are a vital part of programming. They allow a block of code to be executed repeatedly based on a certain condition or until a specific condition is met. In PHP, there are four types of loops - 'while', 'do-while', 'for' and 'foreach'. The 'while' loop continues executing its nested code as long as the condition remains true. The 'do-while' loop executes a block of code at least once, and then either continues executing it or stops, based on the condition. The 'for' loop is often used when the number of iterations is known. The 'foreach' loop works with arrays and is used to loop through each key/value pair in an array. Here's a simple example of a 'for' loop in PHP:
<?php
for ($i = 0; $i < 5; $i++) {
echo $i;
}
?>
In this example, the loop will execute five times, with $i increasing by one each time, outputting the numbers from 0 to 4.
Free resources to learn Loops
- Official docsLoops
Loops: common questions
Can I learn Loops in Hindi?
This lesson is written in English. Once you sign in, open it in the interactive course and ask the AI tutor to explain Loops in Hindi or Hinglish. The tutor answers from this lesson’s own text, so it stays on the syllabus, and it runs on your own Google, OpenAI or Anthropic key.
Is this Loops tutorial for beginners?
It is lesson 39 of 120 in the free PHP roadmap, in stage 6, Loops. If you are new to PHP, start from stage 1 and come back here in order; if you already know the earlier stages, this lesson stands on its own.