The while loop is only executed if the condition is true (as if( condition ) is tested). Obviously, with this way the loop works, its condition must change with each iteration, otherwise it will be an infinite loop. Let’s demonstrate the use of the loop in practice:
$names = ['John', 'Bratt', 'Homer'] $i = 0;//set the initial data for the body of the loop while($i < count($names)) { echo "Name - $names[$i]"; $i++; }
If there is only one statement in the while block, then the curly braces of the block can be removed:
$counter = 0; while(++$i<10) echo $i;
alternative syntax:
$i = 1; while($i<10): echo $i; $i++; endwhile;
Iterating the array using the for loop
list() – assigns values to variables from a list like an array
each() – returns the current element of the array, and then moves the pointer. (Do not support in PHP 8+)
//create array $array[] = 1; $array[] = 2; $array[] = 3; while(list(, $value) = each($array)) { echo $value . '<br>';
Iterating associative array using the while loop
$array['One'] = 1; $array['Two'] = 2; $array['Three'] = 3; while(list($key, $value) = each($array)) { echo $key . '=>' . $value . '<br>'; }
do while loop
The do..while loop is similar to the while loop, only now the loop block is executed, and only then the condition is checked. That is, even if the condition is false, the loop block will be executed at least once:
$counter = 1; do { echo $counter * $counter . "<br />"; $counter++; } while($counter<10)