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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-11-25 07:28:15630browse

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

Checking the Oddity/Evenness of a Number in PHP

Determining if a number is odd or even is a fundamental task in programming. In PHP, the mod operator, represented by the % symbol, provides a straightforward solution to this problem.

When a number is divided by two (using the % operator), the remainder is either 0 (indicating evenness) or a non-zero value (indicating oddness). Therefore, the following expression effectively tests for the number's parity:

$number % 2 == 0

If the remainder is 0, the number is even and the expression will return true. Otherwise, the number is odd, and the expression will return false.

Example Usage:

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

Output:

The number 20 is even.

The above is the detailed content of How Can I Check if a Number is Odd or Even 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