PHP – Prime Number Program | PHP Tutorial

Prime number program in PHP. We would love to share with you how to check whether a given number is prime or not.

In this tutorial, we will create a PHP function to check a given number is prime or not. And we will create a new PHP program with PHP form, that also checks a number is prime or not

What is Prime Number?

Answer: 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

We will create a program in PHP that can check whether a given number is prime or not.

<?php
function IsPrimeOrNot($n)
{
 for($i=2; $i<$n; $i++)
   {
      if($n % $i ==0)
	      {
		   return 0;
		  }
    }
  return 1;
 }
// Pass The Number For check it is prime or not
$a = IsPrimeOrNot(5);
if ($a==0)
 echo 'This is not a Prime Number.....'."\n";
else
 echo 'This is a Prime Number..'."\n";
?>

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) &amp;&amp; $value) {  
     echo 'The Number '. $input . ' is not prime';  
}  else {  
   echo 'The Number '. $input . ' is prime';  
   }   
}  
?>  
</body>  
</html> 

Leave a Reply

Your email address will not be published. Required fields are marked *