Sling Academy
Home/PHP/PHP: Check if a number is a prime number

PHP: Check if a number is a prime number

Last updated: January 09, 2024

Introduction

Prime numbers are the building blocks of the numerical world, with various applications in computer science, cryptography, and mathematics. In PHP, checking whether a number is prime involves multiple approaches, each with their own merits. Discovering prime numbers programmatically can be highly intriguing and an excellent way to familiarize oneself with PHP’s mathematical capabilities.

Understanding Prime Numbers

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The first few prime numbers are 2, 3, 5, 7, 11, and so forth. A common task in programming is validating whether a particular number fits this criterion. In PHP, this requires looping through potential divisors and determining if the number is divisible by any other numbers besides 1 and itself.

Basic Prime Number Check

The simplest way to check for a prime number in PHP is to use a for loop that attempts to divide the number by every smaller number starting from 2:


function isPrime($number) {
    if ($number <= 1) {
        return false;
    }
    for ($i = 2; $i < $number; $i++) {
        if ($number % $i == 0) {
            return false;
        }
    }
    return true;
}

// Example usage:
if (isPrime(29)) {
    echo 'The number is prime.';
} else {
    echo 'The number is not prime.';
}

Optimized Prime Number Check

The basic method is not efficient for larger numbers. An optimized approach checks only up to the square root of the number:


function isPrimeOptimized($number) {
    if ($number <= 1) {
        return false;
    }
    if ($number <= 3) {
        return true;
    }
    if ($number % 2 == 0 || $number % 3 == 0) {
        return false;
    }
    for ($i = 5; $i * $i <= $number; $i += 6) {
        if ($number % $i == 0 || $number % ($i + 2) == 0) {
            return false;
        }
    }
    return true;
}

// Example usage:
if (isPrimeOptimized(29)) {
    echo 'The number is prime.';
} else {
    echo 'The number is not prime.';
}

Prime Number Generation with Sieve of Eratosthenes

When dealing with a range of numbers and wanting to identify all primes within that range, the Sieve of Eratosthenes algorithm is a classic and efficient approach.


function sieveOfEratosthenes($limit) {
    $prime = array_fill(0, $limit + 1, true);
    $prime[0] = $prime[1] = false;
    for ($p = 2; $p * $p <= $limit; $p++) {
        if ($prime[$p]) {
            for ($i = $p * $p; $i <= $limit; $i += $p) {
                $prime[$i] = false;
            }
        }
    }
    return array_filter($prime, function ($isPrime) { return $isPrime; });
}

// Use the function to return all prime numbers up to 30
$primesUpTo30 = sieveOfEratosthenes(30);
print_r(array_keys($primesUpTo30));

Using GMP Functions for Large Numbers

For extremely large numbers, PHP’s GMP (GNU Multiple Precision) functions can be used. The `gmp_prob_prime` function can test primality with a certain degree of certainty:


function isLargeNumberPrime($number) {
    $number = gmp_init($number);
    return gmp_prob_prime($number) > 0;
}

// Example usage
if (isLargeNumberPrime('123456789123456789')) {
    echo 'The number is probably prime.';
} else {
    echo 'The number is probably not prime.';
}

Conclusion

In PHP, determining if a number is prime can range from simple loop structures to the usage of specialized algorithms and functions for handling larger values. Different methods suit different needs, allowing developers to balance between accuracy and performance. Equipped with these techniques, you’re now ready to implement prime number checks in your PHP projects efficiently.

Next Article: PHP: Check if a Number is Integer or Float

Previous Article: PHP: Extracting Numbers from Text (3 Approaches)

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