PHP Exercises: Check two given integers and return the value whichever value is nearest to 13 without going over
57. Nearest to 13 Without Overrun
Write a PHP program to check two given integers and return the value whichever value is nearest to 13 without going over. Return 0 if both numbers go over.
Sample Solution:
PHP Code :
<?php
// Define a function named 'test' that takes two parameters and returns a value based on conditions
function test($x, $y)
{
// Check if both $x and $y are greater than 13; if true, return 0
if ($x > 13 && $y > 13) return 0;
// Check if $x is less than or equal to 13 and $y is greater than 13; if true, return $x
if ($x <= 13 && $y > 13) return $x;
// Check if $y is less than or equal to 13 and $x is greater than 13; if true, return $y
if ($y <= 13 && $x > 13) return $y;
// If none of the above conditions are met, return the greater of $x and $y
return $x > $y ? $x : $y;
}
// Test the 'test' function with different input values and display the results
echo (test(4, 5))."\n";
echo (test(7, 12))."\n";
echo (test(10, 13))."\n";
echo (test(17, 33))."\n";
?>
Explanation:
- Function Purpose:
- The test function takes two parameters, $x and $y, and returns a value based on several conditions involving the numbers' relationship to 13.
- Conditions:
- If both $x and $y are greater than 13, it returns 0.
- If $x is less than or equal to 13 and $y is greater than 13, it returns $x.
- If $y is less than or equal to 13 and $x is greater than 13, it returns $y.
- If none of the above conditions are met, it returns the greater of $x and $y.
Output:
5 12 13 0
Flowchart:

For more Practice: Solve these Related Problems:
- Write a PHP script to compare two integers and return the one closest to 13 without exceeding 13, returning 0 if both exceed.
- Write a PHP function that evaluates two numbers for proximity to 13 and outputs the nearer value if within limit.
- Write a PHP program to determine the number closest to 13 from two inputs and ignore both if they are above 13.
- Write a PHP script to implement conditional logic that selects the nearest candidate to 13, with a fallback to 0 when both are over.
Go to:
PREV : Sum with Range Nullification Except 13/17.
NEXT : Equal Differences in Three Integers.
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.