# Program to verify whether given number is prime or not using PHP

In this PHP tutorial, you are going to learn about what is prime number and how to write PHP program to verify whether the given number is prime or not.

## T**o check given number is prime or not in PHP**

To check if a given number is prime or not using PHP, as a prerequisite we have to know first what is a prime number.

Prime number is a number which has only two factors 1 and number itself. So to tell whether a number is prime or not we should check its factors and if it has only the two factors then we can tell it has a prime number.

It is a simple program which can be done by following some simple steps.

This program involves some basic knowledge of HTML as we use HTML code to take input.

The steps to check if a given number is prime or not using PHP.

#### Algorithm:

- First we have to create an HTML code to accept input as we can’t accept input directly by PHP.
- Open PHP by using <?php.
- Create variables to store values which are sent from html code.
- Now initialize prime number code.
- Create condition such that if we enter zero we get an error message.
- And if the entered number is other than 0 we take a for loop such that it starts from 2(x=2 as every number has min 2 factors) to n-1 where n is given number.
- Now if our number divided by x if leaves remainder 0 then we have to increment c(variable to count no of divisors other).
- Next exit from for loop and initialize a condition such as if c is 0 print number is prime number.
- Else not a prime number.
- Close PHP using ?>.

### PHP code for prime number:

<html> <body> <form method='post'> enter a number<input type="text" name="a"> <input type="submit" name="submit"> </form> </body> </html> <?php $b=$_POST["a"]; $c=0; if(isset($_POST["submit"])) { if($b==0) { echo "enter number other than 0"; exit(); } for($i=2;$i<$b;$i++) { if($b%$i==0) $c++; } if($c==0) echo "$b is a prime number"; else echo "$b not a prime number"; }?>

#### Output:

enter a number 5 [submit]

5 is a prime number

You can also read:

## Leave a Reply

You must be logged in to post a comment.