In this post, we will learn how to check if a number is odd or even in PHP. Before this, let us see what is even and odd number.

## What is Even or Odd Number ?

**Even :**If a number is divisible by 2, then that number is called

**Even**. For example 2, 4, 6, 8... These numbers are divisible by 2.

**Odd :**If a number is not divisible by 2, then that number is called

**Odd**. For example 1, 3, 5, 7... These numbers are not divisible by 2.

## Check If A Number is Even or Odd in PHP

To check if a number is even or odd in PHP, we follow the following code:

$n = 4;

if($n % 2 == 0) {

echo "Even";

} else {

echo "Odd";

}

?>

**code-box**

**Output :**

if $n = 4, then output is

**Even**if $n = 5, then output is

**Odd**## Check If A Number is Even or Odd with Form

To check if a number is even or odd with form, we follow the following code. With this help of we can check multiple number dynamically.

<html>

<body>

<?php

if(isset($_POST['submit'])){

$n = $_POST['number'];

if($n % 2 == 0) {

echo "Even";

} else {

echo "Odd";

}

}

?>

<form method="POST">

<input type="number" name="number" required/>

<input type="submit" name="submit" value="Submit"/>

</form>

</body>

</html>

**code-box**

**Output :**

The output will be received according to the input value.

## Get All Even Odd Numbers from a Range

To get all even or odd numbers form a range like 1 to 10, we follow the following code:

<html>

<body>

<?php

// variables for store odd or even numbers

$even = "";

$odd = "";

if(isset($_POST['submit'])){

$n = $_POST['number'];

for($i = 1; $i <= $n; $i++) {

if($n % 2 == 0) {

$even.=$i."," ;

} else {

$odd.=$i."," ;

}

}

//remove comma(,) from right side

$even = rtrim($even, ",");

$odd = rtrim($odd, ",");

echo "Even : ".$even."<br/>";

echo "Odd : ".$odd;

}

?>

<form method="POST">

<input type="number" name="number" required/>

<input type="submit" name="submit" value="Submit"/>

</form>

</body>

</html>

**code-box**

**Output :**

if we input 10 then we get output as follows:

Even : 2,4,6,8,10

Odd : 1,3,5,7,9

## Summary

In this post we learn how to check if a number is odd or even in PHP. You try to make it yourself. I hope you make. If you face any problem, then comment and tell us. Keep visiting the blog to read more similar posts.

## Post a Comment