PHP Program to Check Even or Odd Number
Use the modulus operator
% in PHP to check if a number is even or odd: if $number % 2 == 0, it is even; otherwise, it is odd.Examples
Input4
Output4 is even
Input7
Output7 is odd
Input0
Output0 is even
How to Think About It
To check if a number is even or odd, divide it by 2 and look at the remainder. If the remainder is 0, the number is even because it divides evenly by 2. If the remainder is 1, the number is odd because it leaves a remainder when divided by 2.
Algorithm
1
Get the input number.2
Calculate the remainder when the number is divided by 2.3
If the remainder is 0, print that the number is even.4
Otherwise, print that the number is odd.Code
php
<?php $number = 7; if ($number % 2 == 0) { echo "$number is even"; } else { echo "$number is odd"; } ?>
Output
7 is odd
Dry Run
Let's trace the number 7 through the code to check if it is even or odd.
1
Assign number
$number = 7
2
Calculate remainder
7 % 2 = 1
3
Check remainder
Since remainder is 1, number is odd
4
Print result
Output: '7 is odd'
| Step | Operation | Value |
|---|---|---|
| 1 | Assign number | 7 |
| 2 | Calculate 7 % 2 | 1 |
| 3 | Check if remainder == 0 | False |
| 4 | Print output | 7 is odd |
Why This Works
Step 1: Use modulus operator
The % operator gives the remainder of division, which helps determine evenness.
Step 2: Check remainder
If remainder is 0, the number divides evenly by 2 and is even.
Step 3: Print result
Based on the remainder, print whether the number is even or odd.
Alternative Approaches
Using bitwise AND operator
php
<?php $number = 7; if (($number & 1) == 0) { echo "$number is even"; } else { echo "$number is odd"; } ?>
This method uses bitwise AND to check the last binary bit; it's fast but less intuitive for beginners.
Using ternary operator
php
<?php $number = 7; echo ($number % 2 == 0) ? "$number is even" : "$number is odd"; ?>
This is a concise way to write the check and print in one line.
Complexity: O(1) time, O(1) space
Time Complexity
The operation uses a single modulus calculation and a comparison, both constant time.
Space Complexity
Only a few variables are used, so space is constant.
Which Approach is Fastest?
Both modulus and bitwise AND methods run in constant time; bitwise may be slightly faster but less readable.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Modulus operator (%) | O(1) | O(1) | Readability and simplicity |
| Bitwise AND (&) | O(1) | O(1) | Performance in low-level operations |
| Ternary operator | O(1) | O(1) | Concise code |
Use
% 2 to quickly check if a number is even or odd in PHP.Beginners often forget to use
== for comparison and use = which assigns instead of compares.