How to usea while loop in PHP
An alternative method is to use a while loop to achieve the same result. This approach is similar to the first approach, but instead of a for loop, a while loop is used. The variable $i is initialized with the start value and incremented in each iteration of the loop. The condition $i % 2 == 0 is used to check for even numbers.
Example: This example shows the use of while loop for printing the even numbers between the given range.
<?php
function printEvenNumbers($start, $end) {
$i = $start;
while ($i <= $end) {
if ($i % 2 == 0) {
echo $i . " ";
}
$i++;
}
}
// Driver code
$start = 1;
$end = 10;
echo "Even numbers between $start and $end are: ";
printEvenNumbers($start, $end);
?>
Output
Even numbers between 1 and 10 are: 2 4 6 8 10
PHP Program to Print All Even Numbers in a Range
Given two numbers, Start and End, the task is to print all even numbers within a given range using PHP. Even numbers are integers that are divisible by 2, meaning they have no remainder when divided by 2.
Examples:
Input: start = 1, end = 10
Output: 2 4 6 8 10
Input: start = 21, end = 35
Output: 22 24 26 28 30 32 34
These are the following approaches:
Table of Content
- Using a for loop
- Using a while loop
- Using array_filter() function