Mastering the while Loop in PHP: A Complete Guide

Rumman Ansari   Software Engineer   2024-07-18 09:19:10   5859  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

 The for loop repeats a segment of code a specific number of times, while the while loop repeats a segment of code an unknown number of times. The while loop works differently than the for loop.

Syntax:



while(condition){
  // execute this code;
  // your code here
}


Example of while loop



<?php
$num = 0;

while($num < 25){
    $num = $num + 5;
    print $num . "<br />";	
}
?>


Output:

The above code will produce the following result-



5
10
15
20
25


In the above code, a variable named num is initialized with the value of 0. The condition in the while loop is that while num is less than 25, 5 should be added to num. Once the value of num is greater than 25, the loop will stop executing.

MCQ Available

There are 3 MCQs available for this topic.

3 MCQ


Stay Ahead of the Curve! Check out these trending topics and sharpen your skills.