php
  1. php-even-or-odd-number

PHP Even or Odd Number

Determining whether a given number is even or odd is a common programming task. In this article, we will see how to write a PHP program to determine whether a number is even or odd.

Syntax

Here's the basic syntax for checking whether a given number is even or odd:

if($number % 2 == 0) {
    echo "$number is even";
} else {
    echo "$number is odd";
}

In the above example, we use the modulus operator % to check if the number is divisible by 2. If the remainder is 0, then the number is even, and if the remainder is 1, then the number is odd.

Example

Here is an example of a PHP program to check whether a given number is even or odd:

<?php
$number = 12;

if($number % 2 == 0) {
    echo "$number is even";
} else {
    echo "$number is odd";
}
?>

Output

The above program will produce the following output:

12 is even

Explanation

In the above example, we assign the value of 12 to the variable $number. We then use the modulus operator % to check if 12 is divisible by 2. Since there is no remainder, we know that 12 is even, and we print the message "12 is even".

If the number were odd, we would print the message "12 is odd".

Use

Determining whether a number is even or odd can be useful in a wide variety of programming tasks. For example, you might need to perform different calculations based on whether a given number is even or odd.

Important Points

  • The modulus operator % can be used to check whether a number is even or odd.
  • If the remainder of a number divided by 2 is 0, then the number is even; otherwise, it is odd.
  • You can use an if-else statement to determine whether a number is even or odd.

Summary

Determining whether a number is even or odd is a common programming task that can be accomplished easily using PHP. We use the modulus operator % to check if the number is divisible by 2 and print the relevant message based on the remainder.

Published on: