The following examples demonstrate Working With Loops in PHP.
The for Loop
Basically, a for loop is an entry-controlled loop. It means, the loop checks the condition before it begins executing any statement. Therefore, if the condition is not true, the control comes out of the loop.
The while Loop
In fact, the while loop is also entry-controlled loop. However, it contains separate statements for initialization, condition, and update of loop control variable.
do…while Loop
Unlike for loop and while loop, the do…while loop is an exit-controlled loop. Therefore, it checks the condition after executing loop statements.
<?php
ini_set('max_execution_time', '300'); //300 seconds = 5 minutes
echo '<h1>Example of Using Loops in PHP</h1>';
$n=12;
echo '<h2>Sum of first n numbers using for loop</h2>';
$sum=0;
for($i=1;$i<=$n;$i++)
{
$sum+=$i;
}
echo '<h3>Sum of first '.$n.' numbers = '.$sum;
echo '<h2>Sum of first n numbers using while loop</h2>';
$n=20;
$sum=0;
$i=1;
while($i<=$n)
{
$sum+=$i;
$i++;
}
echo '<h3>Sum of first '.$n.' numbers = '.$sum;
echo '<h2>Sum of first n numbers using do...while loop</h2>';
$n=15;
$sum=0;
$i=1;
do
{
$sum+=$i;
$i++;
}while($i<=$n);
echo '<h3>Sum of first '.$n.' numbers = '.$sum;
echo '<h2>Display a series of '.$n.' terms using for loop</h2>';
$n=12;
for($i=1,$j=1;$i<=$n;$i++, $j=$i+$j)
{
echo $j.' ';
}
echo '<h2>Display a series of '.$n.' terms using while loop</h2>';
$n=15;
$i=1;
$j=1;
while($i<=$n)
{
echo $j.' ';
$i++;
$j=$i+$j;
}
echo '<h2>Display a series of '.$n.' terms using do...while loop</h2>';
$n=20;
$i=1;
$j=1;
do
{
echo $j.' ';
$i++;
$j=$i+$j;
}while($i<=$n);
echo '<h2>Using break and continue with for loop</h2>';
$n=12;
for($i=1,$j=1;$i<=$n;$i++, $j=$i+$j)
{
if($j%5==0) continue;
if($j%13==0) break;
echo $j.' ';
}
?>
Output
Further Reading
Examples of Array Functions in PHP
- AI
- Android
- Angular
- ASP.NET
- Augmented Reality
- AWS
- Bioinformatics
- Biometrics
- Blockchain
- Bootstrap
- C
- C#
- C++
- Cloud Computing
- Competitions
- Courses
- CSS
- Cyber Security
- Data Science
- Data Structures and Algorithms
- Data Visualization
- Datafication
- Deep Learning
- DevOps
- Digital Forensic
- Digital Trust
- Digital Twins
- Django
- Docker
- Dot Net Framework
- Drones
- Elasticsearch
- ES6
- Extended Reality
- Flutter and Dart
- Full Stack Development
- Git
- Go
- HTML
- Image Processing
- IoT
- IT
- Java
- JavaScript
- Kotlin
- Latex
- Machine Learning
- MEAN Stack
- MERN Stack
- Microservices
- MongoDB
- NodeJS
- PHP
- Power Bi
- Projects
- Python
- Quantum Computing
- React
- Robotics
- Rust
- Scratch 3.0
- Shell Script
- Smart City
- Software
- Solidity
- SQL
- SQLite
- Tecgnology
- Tkinter
- TypeScript
- VB.NET
- Virtual Reality
- Web Designing
- WebAssembly
- XML