Copied!
PHP

How to Check If a Number Is Prime in PHP – Beginner PHP Practice

how-to-check-if-a-number-is-prime-in-php
Shahroz Javed
Jul 22, 2025 . 29 views

Table Of Contents

 

Check Prime Number

This PHP program checks whether a given number is a prime number or not using a basic for loop. It works by checking for divisibility from 2 up to the number itself.

$number = 15;
$isPrime = true;

if ($number <= 1) {
    $isPrime = false;
} else {
    for ($i = 2; $i < $number; $i++) {
        if ($number % $i == 0) {
            $isPrime = false;
            break;
        }
    }
}

echo $isPrime ? "Prime" : "Not Prime";
 

Explanation: A prime number is a number greater than 1 that has no divisors other than 1 and itself. This code first handles numbers less than or equal to 1 as non-prime. Then, it loops from 2 up to n-1 and checks if any number divides the input number evenly. If it finds a divisor, the number is marked as non-prime. If no such divisor is found, the number is declared as prime.

13 Shares

Similar Posts