PHP Exercises: Compute the sum of the two given integers. If one of the given integer value is in the range 10..20 inclusive return 18
44. Sum with Special Range Override (10..20→18)
Write a PHP program to compute the sum of the two given integers. If one of the given integer value is in the range 10..20 inclusive return 18.
Sample Solution:
PHP Code :
<?php
// Define a function that checks if either $x or $y is in the range [10, 20], and returns 18 if true, otherwise returns the sum of $x and $y
function test($x, $y)
{
// Check if $x is in the range [10, 20] OR $y is in the range [10, 20]
// If true, return 18; otherwise, return the sum of $x and $y
return ($x >= 10 && $x <= 20) || ($y >= 10 && $y <= 20) ? 18 : $x + $y;
}
// Test the function with different pairs of numbers
echo test(3, 7)."\n";
echo test(10, 11)."\n";
echo test(10, 20)."\n";
echo test(21, 220)."\n";
?>
Explanation:
- Function Definition:
- The test function checks if either of the numbers $x or $y is within the range [10, 20].
- Condition Checked:
- The function evaluates whether:
- $x is between 10 and 20 (inclusive) OR
- $y is between 10 and 20 (inclusive).
- If either condition is true, the function returns 18.
- If both conditions are false, it returns the sum of $x and $y.
Output:
10 18 18 241
Pictorial Presentation:

Flowchart:

For more Practice: Solve these Related Problems:
- Write a PHP script to sum two integers but return 18 if one of the integers is within the range 10 to 20 inclusive.
- Write a PHP function to compute the sum of two numbers and override the output to 18 if a specific range condition is met.
- Write a PHP program to conditionally adjust the sum of two integers by checking if one input falls within 10 and 20.
- Write a PHP script to use nested conditionals to output 18 when one of the numbers is in a designated range, else display the regular sum.
Go to:
PREV : Within 2 of a Multiple of 10.
NEXT : FizzBuzz String Start with F and/or End with B.
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.