PHP Program to Check Prime Number Example

In this tutorial, we would love to share with you how to check whether a given 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.

How to Check Prime Number in PHP?

Here is the php program 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

To check whether a given number in form is prime or not in php:

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

Recommended PHP Tutorials

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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