Print All Numbers Divisible by 3 and 5 for a Given Number in PHP
Last Updated :
17 Jan, 2024
This article will show you how to print all the numbers less than N, that are divisible by 3 and 5 in PHP. When working with numbers, it’s common to need a program that can identify and print all numbers divisible by specific values. In this article, we will explore different approaches in PHP to print all numbers divisible by 3 and 5 up to a given number.
Using for Loop
The basic method to achieve this is by using a loop to iterate through numbers up to the given limit and checking divisibility.
PHP
<?php
function printDivisibleNumbers( $num ) {
for ( $i = 1; $i <= $num ; $i ++) {
if ( $i % 3 == 0 && $i % 5 == 0) {
echo "$i " ;
}
}
}
$num = 50;
printDivisibleNumbers( $num );
?>
|
Using array_filter() and range() Functions
Another approach involves using array_filter() along with range() to create an array of numbers and filter out those divisible by both 3 and 5.
PHP
<?php
function check3And5Divisible( $number ) {
return ( $number % 3 == 0 && $number % 5 == 0);
}
function printDivisibleNumbers( $num ) {
$numbers = range(1, $num );
$divisibleNumbers =
array_filter ( $numbers , 'check3And5Divisible' );
echo implode( ' ' , $divisibleNumbers );
}
$num = 50;
printDivisibleNumbers( $num );
?>
|
Share your thoughts in the comments
Please Login to comment...