Here’s a simple solution to determine if a number is odd or even in PHP, with error handling for invalid inputs:
<?php
function is_odd($n) {
if (!is_int($n)) {
throw new InvalidArgumentException("Input must be an integer.");
}
return (boolean) ($n % 2);
}
function is_even($n) {
return !is_odd($n);
}
// Test.
for ($i = 1; $i <= 5; $i++) {
echo "$i is " . (is_odd($i) ? 'odd' : 'even') . "<br />";
}
?>
Output
When you run this code, the output in the browser will be:
1 is odd
2 is even
3 is odd
4 is even
5 is odd
Explanation
is_odd($n): This function verifies that the input is an integer. If not, it throws anInvalidArgumentException, since rational numbers are neither odd nor even. If the input is valid, it checks if the number is odd using the modulus operator (%).is_even($n): This function usesis_odd, so we don’t repeat code unnecessarily.- Typecasting: The
is_oddfunction uses typecasting to(boolean)to ensure it consistently returnsTRUEorFALSEinstead of numerical values (1 or 0). - PHP Modulus Operator (
%): The modulus operator calculates the remainder of a division. In PHP, when using modulus, the operands are converted to integers, stripping any decimal parts. So we need to verify the number before using it with the modulus operator.
echo 1.99 % 2; // Outputs 1
Mathematical Explanation
In mathematics, odd and even numbers are defined as follows:
- Odd Numbers: An integer (n) is considered odd if it can be expressed in the form (n = 2k + 1), where (k) is any integer. This means that when divided by 2, the number leaves a remainder of 1.
- Even Numbers: An integer (n) is considered even if it can be expressed as (n = 2k), where (k) is any integer. In this case, when divided by 2, the number leaves no remainder (i.e., a remainder of 0).