PHP function Exercises: Check whether a number is prime or not
2. Prime Number Checker
Write a PHP function to check whether a number is prime or not.
Note: A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Visual Presentation:

Sample Solution:
PHP Code:
<?php
// Function to check if a number is prime
function IsPrime($n)
{
// Loop through all numbers from 2 to n-1
for ($x = 2; $x < $n; $x++)
{
// If n is divisible by any number other than 1 and itself,
// it's not prime, so return 0
if ($n % $x == 0)
{
return 0;
}
}
// If no divisor found, n is prime, so return 1
return 1;
}
// Call the IsPrime function to check if 3 is prime
$a = IsPrime(3);
// Check the return value and print the result
if ($a == 0)
echo 'This is not a Prime Number.....' . "\n";
else
echo 'This is a Prime Number..' . "\n";
?>
Output:
This is a Prime Number..
Explanation:
In the exercise above,
- Define a function named "IsPrime()" which takes an integer parameter '$n'.
- Inside the function, there's a loop that iterates from 2 to one less than '$n'. This loop checks for divisors of '$n'.
- If '$n' is divisible by any number other than 1 and itself, the function returns 0, indicating that the number is not prime.
- If no divisor is found in the loop, the function returns 1, indicating that the number is prime.
- Outside the function, the "IsPrime()" function is called with an argument of 3, and the result is stored in the variable '$a'.
- The code then checks the value of '$a' and prints whether 3 is a prime number or not.
Flowchart :

For more Practice: Solve these Related Problems:
- Write a PHP function to determine if a number is prime by checking divisibility only up to the square root of the number.
- Write a PHP script that uses a for loop to test for prime numbers and returns an array of all primes within a given range.
- Write a PHP function to check for primality using recursion and memoization to optimize repeated checks for multiple inputs.
- Write a PHP program to implement the Sieve of Eratosthenes algorithm and compare its performance with a basic loop-based prime checker.
Go to:
PREV : Factorial Function.
NEXT : String Reversal.
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.