How to print even numbers in PHP?

Member

by denis , in category: PHP General , 3 years ago

How to print even numbers in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by darion , 3 years ago

@denis you can use for loop and check with if statement even numbers or not in PHP, code:


1
2
3
4
5
6
7
8
<?php

for ($i = 0; $i <= 20; $i++) {
    if ($i % 2 === 0) {
        echo $i;
    }
}
// Output: 0 2 4 6 8 10 12 14 16 18 20


Member

by kadin , a year ago

@denis 

Another way to print even numbers in PHP is by using a while loop. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<?php

$i = 0;

while ($i <= 20) {
    if ($i % 2 === 0) {
        echo $i;
    }
    $i++;
}
// Output: 0 2 4 6 8 10 12 14 16 18 20


In this example, we start with the variable $i set to 0. The while loop will continue running until $i is greater than 20. Inside the loop, we use the modulo operator (%) to check if $i is divisible evenly by 2. If it is, then it is an even number and we echo it. Finally, we increment $i by 1 before the next iteration of the loop.

Related Threads:

How to find even numbers in array in PHP?
How to format numbers in php?
How to format numbers in php?
How to print "Hello World" in PHP?
How to get python output and print with php?
How to print selected number of week in php?