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.
Go to:
PREV : Larger with Remainder Rule.
NEXT : Sum with Digit-Length Constraint.
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.