Home >Backend Development >PHP Tutorial >How Can I Determine if a Number is Even or Odd in PHP?

How Can I Determine if a Number is Even or Odd in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-28 08:49:11870browse

How Can I Determine if a Number is Even or Odd in PHP?

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
  • If the expression evaluates to true, $number is even.
  • If it returns false, $number is odd.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn