PHP Exercises: Check two given integers, each in the range 10..99. Return true if a digit appears in both numbers, such as the 3 in 13 and 33
52. Shared Digit in Two Integers
Write a PHP program to check two given integers, each in the range 10..99. Return true if a digit appears in both numbers, such as the 3 in 13 and 33.
Sample Solution:
PHP Code :
<?php
// Define a function named 'test' that checks if the digits of two numbers have any common digit
function test($x, $y)
{
// Check if the tens digit of $x is equal to the tens digit of $y or if the tens digit of $x is equal to the units digit of $y
// or if the units digit of $x is equal to the tens digit of $y or if the units digit of $x is equal to the units digit of $y
return $x / 10 == $y / 10 || $x / 10 == $y % 10 || $x % 10 == $y / 10 || $x % 10 == $y % 10;
}
// Test the 'test' function with different input values and display the results
var_dump(test(11, 21))."\n";
var_dump(test(11, 20))."\n";
var_dump(test(10, 10))."\n";
?>
Explanation:
- Function Definition:
- The test function checks if two numbers, $x and $y, have any common digit.
- Conditions:
- The function compares the digits of $x and $y by splitting them into tens and units places.
- Specifically, it checks if:
- The tens digit of $x is equal to the tens digit of $y.
- The tens digit of $x is equal to the units digit of $y.
- The units digit of $x is equal to the tens digit of $y.
- The units digit of $x is equal to the units digit of $y.
- If any of these conditions are met, it returns true; otherwise, it returns false.
Output:
bool(true) bool(false) bool(true)
Flowchart:

For more Practice: Solve these Related Problems:
- Write a PHP script to check if any digit from the first two-digit number appears in the second two-digit number using string conversion.
- Write a PHP function that compares each digit of two numbers in the range 10 to 99 and returns true if any digit is common.
- Write a PHP program to extract digits from two integers and determine if there exists an intersection between their digit sets.
- Write a PHP script to compare two numbers digit by digit and output a boolean true if they share at least one digit.
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a PHP program to find the larger from two given integers. However if the two integers have the same remainder when divided by 7, then the return the smaller integer. If the two integers are the same, return 0.
Next: Write a PHP program to compute the sum of two given non-negative integers x and y as long as the sum has the same number of digits as x. If the sum has more digits than x then return x without y.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.