PHP Exercises: Check if a given number is within 2 of a multiple of 10
43. Within 2 of a Multiple of 10
Write a PHP program to check if a given number is within 2 of a multiple of 10.
Sample Solution:
PHP Code :
<?php
// Define a function that checks if the last digit of a number is less than or equal to 2 OR greater than or equal to 8
function test($n)
{
// Check if the remainder of $n divided by 10 is less than or equal to 2 OR greater than or equal to 8
return $n % 10 <= 2 || $n % 10 >= 8;
}
// Test the function with different values
var_dump(test(3));
var_dump(test(7));
var_dump(test(8));
var_dump(test(21));
?>
Explanation:
- Function Definition:
- The test function checks if the last digit of a given number $n is within a specific range.
- Condition Checked:
- The function evaluates whether the last digit of $n:
- Is less than or equal to 2 (i.e., $n % 10 <= 2), OR
- Is greater than or equal to 8 (i.e., $n % 10 >= 8).
- This is done by checking the remainder when $n is divided by 10, which gives the last digit of $n.
Output:
bool(false) bool(false) bool(true) bool(true)
Flowchart:

For more Practice: Solve these Related Problems:
- Write a PHP script to test if a given number is within 2 of any multiple of 10 using modulo operations and absolute difference comparisons.
- Write a PHP function to iterate through possible multiples of 10 and determine if the input falls within a tolerance of ±2.
- Write a PHP program to check proximity to the nearest multiple of 10 by computing the difference and comparing it with 2.
- Write a PHP script to simulate the condition by rounding to the nearest ten and verifying if the absolute difference is less than or equal to 2.
Go to:
PREV : Multiple of 3 or 7 but Not Both.
NEXT : Sum with Special Range Override (10..20?18).
PHP Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.