Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to check if a number is even

Short answer

An even number leaves a remainder of zero when divided by 2:

<?php
 
$number = 10;
 
var_dump($number % 2 === 0);

Output:

bool(true)

A reusable function

It is convenient to move the check into a function with a clear name:

<?php
 
function isEven(int $number): bool
{
    return $number % 2 === 0;
}
 
var_dump(isEven(7));
var_dump(isEven(0));

Output:

bool(false)
bool(true)

Divisibility by another number

The same technique checks divisibility by any other number:

<?php
 
var_dump(15 % 5 === 0);
var_dump(16 % 5 === 0);

Output:

bool(true)
bool(false)

Functions used in this recipe

  • intdiv — Performs integer division.

Thanks for reading!

Donate to the site — we work hard for you.