w3resource

PHP Exercises: Check whether two given integers are in the range 40..50 inclusive


20. Check Integers in Range 40..50 or 50..60

Write a PHP program to check whether two given integers are in the range 40..50 inclusive, or they are both in the range 50..60 inclusive.

Sample Solution:

PHP Code :

<?php
// Define a function that checks if a point is within one of two rectangular regions
function test($x, $y) 
{
    // Check if the point is within the first rectangular region
    $condition1 = ($x >= 40 && $x <= 50 && $y >= 40 && $y <= 50);
    
    // Check if the point is within the second rectangular region
    $condition2 = ($x >= 50 && $x <= 60 && $y >= 50 && $y <= 60);
    
    // Return true if the point is within either region, otherwise false
    return $condition1 || $condition2;
}

// Test the function with different sets of coordinates
var_dump(test(78, 95));
var_dump(test(25, 35));
var_dump(test(40, 50));
var_dump(test(55, 60));
?>

Explanation:

  • Function Definition:
    • The test function takes two parameters, $x and $y, representing the coordinates of a point.
  • Region Checks:
    • First Rectangle (condition1): Checks if the point is within the rectangle bounded by x = 40 to 50 and y = 40 to 50.
    • Second Rectangle (condition2): Checks if the point is within the rectangle bounded by x = 50 to 60 and y = 50 to 60.
  • Return Value:
    • The function returns true if the point lies within either of the two rectangles; otherwise, it returns false.
  • Function Calls and Results:
    • First Call: test(78, 95) returns false as (78, 95) is outside both regions.
    • Second Call: test(25, 35) returns false as (25, 35) is outside both regions.
    • Third Call: test(40, 50) returns true as (40, 50) is within the first region.
    • Fourth Call: test(55, 60) returns true as (55, 60) is within the second region.

Output:

bool(false)
bool(false)
bool(true)
bool(true)

Flowchart:

Flowchart: Check whether two given integers are in the range 40..50 inclusive.

For more Practice: Solve these Related Problems:

  • Write a PHP script to verify if two integers both fall within 40–50 or both within 50–60, returning a boolean accordingly.
  • Write a PHP function that tests two numbers for dual-range membership (either both in 40–50 or both in 50–60) using logical operators.
  • Write a PHP program to check two inputs against two distinct ranges and output true only if both lie in one common range.
  • Write a PHP script to apply compound condition checks for two numbers to decide if they are in matching specific ranges.

Go to:


PREV : Largest of Three Integers.
NEXT : Largest in Range 20..30.

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.



Follow us on Facebook and Twitter for latest update.