Are you a school / college student? then you are at the right place to learn something new.

Today you are going to learn how to find Odd or Even number in PHP.

To find the even number it is pretty basic, any number divisible by 2 is an even number

for eg:

10 ÷ 2 = 5, 5 is the quotient, reminder is 0

so, if the reminder is 0 (zero) then it is an **even** number other it is an **odd** number.

In PHP there are two operators (/) slash and (%) percentage, former one returns the quotient and the later one returns the reminder.

In our program we need to find the reminder to check whether the entered number is odd or even, the basic script would be this:

1 2 3 4 5 |
if(($number % 2) == 0){ echo "You entered an Even number"; }else{ echo "You entered an Odd number"; } |

You got an Idea how the script will work right?

Here is the complete code for you:

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 |
<html> <body> <h3>Odd or Even PHP Example</h3> <form action="" method="post"> <label>Enter a number</label><input type="text" name="number" /> <input type="submit" /> </form> </body> </html> <?php if($_POST){ $number = $_POST['number']; //check if the enter value is a number or throw an error if (!(is_numeric($number) && is_int(0+$number))){ echo "<p style='color:red;'>Error: You entered a string. Please enter an Integer</p>"; die(); } //divide the entered number by 2 //if the reminder is 0 then the number is even otherwise the number is odd if(($number % 2) == 0){ echo "You entered an Even number"; }else{ echo "You entered an Odd number"; } } ?> |

And a demo:

Thanks alot it is very simaple way for understand code.

it’s very easy to understand …thanks

it is easy way to understandble to any one

Why do you need to have the 0+$number for this to work? If I use it without the 0+, it breaks the code. I don’t understand the need for the 0+

How could you adjust the code to accept a number string such as 1, 4, 7, 9, 16, 18