What potential logic errors can occur when testing for prime numbers in PHP?
One potential logic error when testing for prime numbers in PHP is not properly handling edge cases, such as checking if the number is less than 2. To solve this, you should add a condition to return false if the number is less than 2. Additionally, you should only loop up to the square root of the number to improve efficiency.
function isPrime($num) {
if ($num < 2) {
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';
}