PHP Exercises: Check if a given non-negative given number is a multiple of 3 or 7, but not both
42. Multiple of 3 or 7 but Not Both
Write a PHP program to check if a given non-negative given number is a multiple of 3 or 7, but not both.
Sample Solution:
PHP Code :
<?php
// Define a function that checks if a number satisfies an exclusive OR (^) condition involving modulo operations
function test($n)
{
// Check if the remainder of $n divided by 3 is 0 XOR the remainder of $n divided by 7 is 0
return ($n % 3 == 0) ^ ($n % 7 == 0);
}
// Test the function with different values
var_dump(test(3));
var_dump(test(7));
var_dump(test(21));
?>
Explanation:
- Function Definition:
- The test function checks if a given number $n satisfies a specific condition using the exclusive OR (XOR) operator ^ with modulo operations.
- Condition Checked:
- The function evaluates whether:
- $n is divisible by 3 (i.e., $n % 3 == 0), XOR
- $n is divisible by 7 (i.e., $n % 7 == 0).
- The XOR operator returns true only if one of these conditions is true but not both.
- If either condition is met exclusively, the function returns true; otherwise, it returns false.
Output:
int(1) int(1) int(0)
Visual Presentation:

Flowchart:

For more Practice: Solve these Related Problems:
- Write a PHP script to verify if a non-negative number is a multiple of 3 or 7 exclusively, ensuring it is not divisible by both.
- Write a PHP function to test the divisibility of a number by 3 and 7 and return 1 if only one condition is met, or 0 otherwise.
- Write a PHP program to check for exclusive multiplicity by computing remainders for both 3 and 7 and applying XOR logic.
- Write a PHP script to use custom logic without built-in functions to determine if a number is divisible by 3 or 7 but not simultaneously.
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a PHP program to test if a given non-negative number is a multiple of 13 or it is one more than a multiple of 13.
Next: Write a PHP program to check if a given number is within 2 of a multiple of 10.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.