PHP Program to Check Whether a Number is Prime or Not

Prime number program in PHP tutorial, you will learn how to check whether an integer entered by the user is a prime number or not.

In below example of we will check a given number is prime or not using php function also we have added PHP form where you can check to enter a number is prime or not.

What is Prime Number?

A number that is only divisible by 1 and itself is called a prime number. The first few prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23 and 29.

Prime number program in PHP

The below example check whether a number is Prime or Not.

<?php
function IsPrimeOrNot($n)
{
   for($i=2; $i<$n; $i++) {
      if ($n % $i ==0) {
           return 0;
       }
   }
  return 1;
 }

$result = IsPrimeOrNot(5);

if ($result==0)
 echo 'This is not a Prime Number.';
else
 echo 'This is a Prime Number.';
?>

Prime Number using Form in PHP

Here we will create PHP program with PHP Forms for how to check a whether a given number is prime or not.

<html>  
<head>  
<title>Prime Number using Form in PHP</title>  
</head>  
<body>  
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> 
Enter a Number: <input type="text" name="input"><br><br>  
<input type="submit" name="submit" value="Submit">  
</form>  
<?php 
if($_POST)  
{  
    $input=$_POST['input'];  
    for ($i = 2; $i <= $input-1; $i++) {  
      if ($input % $i == 0) {  
      $value= True;  
      }  
}  
if (isset($value) && $value) {  
     echo 'The Number '. $input . ' is not prime';  
}  else {  
   echo 'The Number '. $input . ' is prime';  
   }   
}  
?>  
</body>  
</html> 

PHP program to get prime numbers between 1 and 100

Here, we have created a function ‘checkPrime()‘ to check whether the number is prime or not. We loop over the number range (1 to 100) and pass each as a parameter to the function to check whether a number is prime or not.

<?php
function checkPrime($num)
{
   if ($num == 1)
   return 0;
   for ($i = 2; $i <= $num/2; $i++)
   {
      if ($num % $i == 0)
      return 0;
   }
   return 1;
}

echo '<h2>Prime Numbers between 1 and 100</h2> ';
for($num = 1; $num <= 100; $num++) {
	$flag = checkPrime($num);
	if ($flag == 1) {
		echo $num." ";
	}	
}  
?>

I hope you live prime number program in php.

Leave a Comment