PHP Exercises: Find the larger value from two positive integer values that is in the range 20..30 inclusive
PHP Basic Algorithm: Exercise-21 with Solution
Write a PHP program to find the larger value from two positive integer values that is in the range 20..30 inclusive, or return 0 if neither is in that range.
Sample Solution:
PHP Code :
<?php
// Define a function that compares two values based on certain conditions
function test($x, $y)
{
// Check if both $x and $y are within the range of 20 to 30
if ($x >= 20 && $x <= 30 && $y >= 20 && $y <= 30) {
// Compare $x and $y, return the greater value
if ($x >= $y) {
return $x;
} else {
return $y;
}
} elseif ($x >= 20 && $y <= 30) {
// Check if only $x is within the range, return $x
return $x;
} elseif ($y >= 20 && $y <= 30) {
// Check if only $y is within the range, return $y
return $y;
} else {
// Return 0 if neither condition is met
return 0;
}
}
// Test the function with different sets of coordinates
echo test(78, 95)."\n";
echo test(20, 30)."\n";
echo test(21, 25)."\n";
echo test(28, 28)."\n";
?>
Sample Output:
0 30 25 28
Visual Presentation:
Flowchart:
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a PHP program to check which number nearest to the value 100 among two given integers. Return 0 if the two numbers are equal.
Next: Write a PHP program to check if a given string contains between 2 and 4 'z' character.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics