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
Release: 2024-11-25 07:28:15
Original
649 people have browsed it

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
Copy after login

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.";
}
Copy after login

Output:

The number 20 is even.
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template