Determining Even versus Odd Numbers:
Determining whether a given number is odd or even in PHP is a fundamental task. The most straightforward approach involves utilizing the modulo operator (%).
Modulus Operator Approach:
The modulo operator, represented by %, calculates the remainder after dividing one number by another. When a number is divided by 2, an even number will yield a remainder of 0, while an odd number will have a remainder of 1.
Therefore, the following expression checks if a variable $number is even or odd:
$number % 2 == 0
Example:
$number = 20; if ($number % 2 == 0) { echo "It's even"; } else { echo "It's odd"; }
Output:
It's even
The above is the detailed content of How Can I Determine if a Number is Even or Odd in PHP?. For more information, please follow other related articles on the PHP Chinese website!