Checking If a Number Is Prime in PHP


Simple function to check if a number is prime.

Source Code

function isPrime($num) {
    if ($num <= 1) {
        return false;
    }
    for ($i = 2; $i <= sqrt($num); $i++) {
        if ($num % $i == 0) {
            return false;
        }
    }
    return true;
}
echo isPrime(5) ? "Prime" : "Not prime";
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments