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
Release: 2024-11-28 08:49:11
Original
818 people have browsed it

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

Output:

It's even
Copy after login

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!

source:php.cn
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