How to Check If a Number is Prime in PHP

09/09/2021

Contents

In this article, you will learn how to check if a number is prime in PHP.

Example

Here is an example code for checking if a number is prime in PHP:

<?php
  function is_prime($num) {
    if ($num <= 1) {
        return false;
    }

    for ($i = 2; $i < $num; $i++) {
        if ($num % $i == 0) {
            return false;
        }
    }

    return true;
  }
?>

In the example code, the function is_prime takes a single argument $num, which is the number we want to check for primality.

The first line of the function checks if the number is less than or equal to 1, and if so, returns false. This is because 1 is not considered a prime number.

The next section of the code uses a for loop to iterate over numbers from 2 to $num - 1. The loop checks if $num is divisible by the current iteration number using the modulo operator %. If $num is divisible by the current iteration number, the function returns false immediately, indicating that $num is not a prime number.

If the loop completes without finding any divisors, the function returns true, indicating that $num is prime.