Check if a number is prime using PHP

The below function named checkPrime() uses a modulus (remainder) to check if a provided number is prime. You can update the “return” lines to provide a more pragmatic response (like TRUE or FALSE), or just echo it out as shown. In the specific example, we’re checking if the number 989 is prime, but you can replace the number on the second-to-last line to check against any number.
<?php
function checkPrime($n){
    for ($x = 2; $x <= $n/2; $x++) {
        if ($n % $x == 0){
            return "no, divisible by " . $x;
        }
    }
    return "yes";
}
echo checkPrime(989);
?>                                            

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>