Write a PHP program to check whether a number is even or odd using if else. How to check whether a number is even or odd using if else in PHP program. PHP Program to input a number from user and check whether the given number is even or odd. Logic to check even and odd number using if...else
in PHP programming.
Output:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | <?php $num = $_POST['number'] ??'0'; /* Check if the number is divisible by 2 then it is even */ if($num % 2 == 0) { /* num % 2 is 0 */ $result="$num is Even."; } else { /* num % 2 is 1 */ $result= "$num is Odd."; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>PHP Examples </title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> </head> <body> <div class="container"> <form method="post" action="<?=$_SERVER["PHP_SELF"]?>"> <div class="form-group"> <label for="number">Enter any number to check even or odd:</label> <input type="number" class="form-control" name="number" id="number" value="<?=$num?>" > </div> <button type="submit" class="btn btn-default">Check</button> </form> <div class="col"> <div class="col-12"> <h1><?=$result?></h1> </div> </div> </div> </body> </html> |
A number exactly divisible by 2 leaving no remainder, is known as even number. Programmatically, if any number modulo divided by 2 equals to 0 then, the number is even otherwise odd.
Step by step descriptive logic to check whether a number is even or odd.
Input a number from user. Store it in some variable say num.
Check if number modulo division equal to 0 or not i.e. if(num % 2 == 0) then the number is even otherwise odd.