In what ways can PHP code be optimized for better performance when checking for prime numbers?

To optimize PHP code for better performance when checking for prime numbers, one approach is to reduce the number of iterations needed to check for factors. Instead of iterating up to the number itself, we can iterate up to the square root of the number, as factors repeat after this point. This optimization can significantly reduce the number of iterations required for prime number checking.

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

// Test the function
$num = 17;
if(isPrime($num)){
    echo $num . " is a prime number.";
} else {
    echo $num . " is not a prime number.";
}