The while Construct
The while
construct creates a loop that executes as long as
the condition evaluates to true
. The condition is checked before each iteration.
If the condition is false from the very beginning, the loop will not execute even once.
Syntax
while (condition) {
// code to be executed
}
Example
Let's output numbers from 1
to 5
:
<?php
$i = 1;
while ($i <= 5) {
echo $i;
$i++;
}
?>
Code execution result:
12345
Example
Processing array elements:
<?php
$arr = [1, 2, 3, 4, 5];
$i = 0;
while ($i < count($arr)) {
echo $arr[$i] * 2;
$i++;
}
?>
Code execution result:
246810
Example
Infinite loop:
<?php
while (true) {
// infinite loop
}
?>
This code will run indefinitely until it is forcibly stopped.