I have two integers for example "12345" and "98754", they have a count of 2 matching numbers namely 4 and 5, the order doesnt matter.
Now: How do I check something like that in PHP?
I have two integers for example "12345" and "98754", they have a count of 2 matching numbers namely 4 and 5, the order doesnt matter.
Now: How do I check something like that in PHP?
You can split the inputs to arrays and use array_intersect to find matching numbers.
$a = 12345;
$b = 98754;
//Create arrays of the numbers
$a = str_split($a);
$b = str_split($b);
// Find matching numbers
$matching = array_intersect($a, $b);
Var_dump($matching);
// Output: 4,5
Echo count($matching);
// Output: 2
Edit: Code-centric solution:
$a = 1231534;
$b = 89058430;
$matches = compare( $a, $b );
print count($matches);
function compare ( $a, $b ) {
$str_a = (string) $a;
$str_b = (string) $b;
$matches = [];
for($i=0;$i<=9;$i++) {
if (strstr($str_a, (string)$i) && strstr($str_b,(string)$i)) $matches[] = $i;
}
return $matches;
}
Added an example here that counts digits that occur in both numbers. If multiple digits occur in both, these are included:
<?php
function digits_in_both($x, $y)
{
$in_both = [];
$split_y = str_split($y);
foreach(str_split($x) as $n) {
$key = array_search($n, $split_y);
if($key !== false) {
$in_both[] = $n;
unset($split_y[$key]);
}
}
return $in_both;
}
$in_both = digits_in_both(123445, 4456);
var_export($in_both);
var_dump(count($in_both));
Output:
array (
0 => '4',
1 => '4',
2 => '5',
)int(3)
Contrary to what you expect with array_intersect, order matters as demonstrated here:
var_export(array_intersect(str_split('024688'), str_split('248')));
var_export(array_intersect(str_split('248'), str_split('024688')));
Output:
array (
1 => '2',
2 => '4',
4 => '8',
5 => '8',
)array (
0 => '2',
1 => '4',
2 => '8',
)