How to usearray_filter() function in PHP
For a more concise solution, we can use the range function in PHP to generate an array of numbers within the specified range and then filter out the even numbers. The range function generates an array of numbers from $start to $end. The array_filter() function is used to filter out the even numbers. It takes the generated array and a callback function that returns true for even numbers. The implode function is used to convert the array of even numbers into a string, separated by spaces, for printing.
Example: This example shows the use of array_filter() function for printing the even numbers between the given range.
<?php
function printEvenNumbers($start, $end) {
$numbers = range($start, $end);
$evenNumbers = array_filter($numbers, function($number) {
return $number % 2 == 0;
});
echo implode(" ", $evenNumbers);
}
// 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