What are some tips for optimizing prime number search in PHP code?

When searching for prime numbers in PHP, one way to optimize the process is to only check divisibility up to the square root of the number being tested. This is because if a number n is not a prime, it can be factored into two factors, one of which must be less than or equal to the square root of n. By limiting the divisibility check to the square root, we can significantly reduce the number of iterations required.

function isPrime($num) {
    if ($num <= 1) {
        return false;
    }
    
    for ($i = 2; $i <= sqrt($num); $i++) {
        if ($num % $i == 0) {
            return false;
        }
    }
    
    return true;
}

// Example usage
$num = 29;
if (isPrime($num)) {
    echo $num . ' is a prime number';
} else {
    echo $num . ' is not a prime number';
}