PHP program to find Odd or Even number Example

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:

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:

<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:

demo

 

5 thoughts on “PHP program to find Odd or Even number Example”

  1. 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+

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top