Sling Academy
Home/PHP/PHP: Checking if a Number is Odd or Even

PHP: Checking if a Number is Odd or Even

Last updated: January 09, 2024

Introduction

Determining whether a number is odd or even is a fundamental concept in programming and can be easily accomplished in PHP. This tutorial will guide you through various methods, from basic to advanced, to perform this check efficiently.

Basic Method Using Modulus Operator

The most straightforward approach to check if a number is odd or even in PHP is by using the modulus operator %. This operator gives the remainder of the division of two numbers. An even number will have a remainder of 0 when divided by 2, while an odd number will have a remainder of 1.

<?php
function isEven($num) {
    return $num % 2 == 0;
}

function isOdd($num) {
    return $num % 2 != 0;
}

// Example usage:
$number = 5;
if (isEven($number)) {
    echo "{$number} is even.";
} else {
    echo "{$number} is odd.";
}
?>

Using Bitwise Operators

In computer science, bitwise operations are very efficient for performing certain tasks. To check if a number is even or odd, you can look at the last bit of its binary representation. If the last bit is 0, the number is even, and if it’s 1, the number is odd.

<?php
function isEvenBitwise($num) {
    return ($num & 1) == 0;
}

function isOddBitwise($num) {
    return ($num & 1) == 1;
}

// Example usage:
$number = 5;
if (isEvenBitwise($number)) {
    echo "{$number} is even.";
} else {
    echo "{$number} is odd.";
}
?>

Abstracting to a Single Function

We can combine the check into a single function and return a string that describes whether the number is odd or even. Such abstraction can make our code cleaner and more reusable.

<?php
function checkNumber($num) {
    return ($num % 2 == 0) ? "even" : "odd";
}

// Example usage:
$number = 5;
echo "{$number} is " . checkNumber($number) . ".";
?>

Advanced: Creating a Number Checker Class

For a more advanced usage, we could encapsulate the logic of checking numbers into a class. This provides us with the flexibility of extending the class in the future as well as grouping related functionalities together.

<?php

class NumberChecker {
    private $number;

    public function __construct($number) {
        $this->number = $number;
    }

    public function isEven() {
        return $this->number % 2 == 0;
    }

    public function isOdd() {
        return $this->number % 2 != 0;
    }

    public function getDescription() {
        return "The number {$this->number} is " . ($this->isEven() ? 'even' : 'odd') . ".";
    }
}

// Example usage:
$checker = new NumberChecker(5);
echo $checker->getDescription();

?>

Utilizing Functional Programming Concepts

PHP supports functional programming concepts, and we can leverage these with anonymous functions and higher-order functions. Below, we dynamically decide if a number should be checked for evenness or oddness.

<?php

$checkEven = function($num) {
    return $num % 2 == 0;
};

$checkOdd = function($num) {
    return $num % 2 != 0;
};

function checkNumber($num, callable $checker) {
    return $checker($num) ? 'True' : 'False';
}

// Example usage:
$number = 5;
echo "Is {$number} odd? " . checkNumber($number, $checkOdd);

?>

Performance Considerations

Although all the provided methods are highly efficient for this simple task, it is always good practice to think about performance. In applications where performance is a critical factor, bitwise operations can offer a slight advantage over modulus operator due to lower-level operations directly on bits.

Summary

In this tutorial, we’ve explored different ways to determine if a number is odd or even in PHP. From the basic modulus method to more advanced concepts like functional programming, PHP provides us with the flexibility to incorporate these checks elegantly into our codebase.

Next Article: PHP: Formatting thousand, million as K, M (e.g. 1k, 2m)

Previous Article: PHP: Adding suffixes to numbers (e.g. 1st, 2nd, 3rd, 4th)

Series: Working with Numbers and Strings in PHP

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array