# PHP Program to Check Prime Number

Last Updated:

## What is Prime Number?

A positive integer that is divisible only by itself and 1.

Tips: It is recommended to use our online Prime Numbers calculator for better understanding.

## Examples

The following table provides few examples of prime numbers.

NumberDivisorResult
13 1, 13 Prime Number
15 1, 3, 5, 15 Not a Prime Number
47 1, 47 Prime Number

## Using for loop

In the following example, we will check whether the given number (7) is a Prime number or not using for loop.

### Example

PHP Compiler
<?php \$num = 7; \$count = 0; for(\$i=1; \$i<=\$num; \$i++) { if(\$num % \$i == 0) \$count++; } if(\$count == 2) echo "\$num is a prime number"; else echo "\$num is not a prime number"; ?>

## Using while loop

In the following example, we will check whether the given number (7) is a Prime number or not using while loop.

### Example

PHP Compiler
<?php \$num = 7; \$i = 1; \$count = 0; while(\$num >= \$i) { if(\$num % \$i == 0) \$count++; \$i++; } if(\$count == 2) echo "\$num is a prime number"; else echo "\$num is not a prime number"; ?>

## Using do while loop

In the following example, we will check whether the given number (7) is a Prime number or not using do while loop.

### Example

PHP Compiler
<?php \$num = 7; \$i = 1; \$count = 0; do{ if(\$num % \$i == 0) \$count++; \$i++; }while(\$i<= \$num); if(\$count == 2) echo "\$num is a prime number"; else echo "\$num is not a prime number"; ?>

## Prime Numbers between the Given Range

In the following example, we will find all the Prime numbers between 1 and 20.

### Example

PHP Compiler
<?php \$start = 1; \$end = 20; \$count = 0; \$flag = 0; \$i = 1; echo "Prime numbers between \$start and \$end: <br>"; for(\$start=\$start; \$start<=\$end; \$start++) { for(\$i=1; \$i<=\$start; \$i++) { if(\$start % \$i == 0) \$count++; } if(\$count == 2) { \$flag = 1; echo "\$start "; } \$count = 0; } if(\$flag == 0) echo "There is no Prime numbers between the given series"; ?>

## Check Whether the Given Number is Prime or Composite

In the following example, we will check whether the given number is a Prime number or Composite number.

### Example

PHP Compiler
<?php \$num = 11; \$count = 0; for(\$i=1; \$i<=\$num; \$i++) { if(\$num % \$i == 0) \$count++; } if(\$count == 2) echo "\$num is a prime number"; else echo "\$num is a composite number"; ?>