Skip to content
Advertisement

how to compare numbers from array elements then get common numbers from start php

Problem 1:
array(670006151,670006152,670006251)
output: 670006151,152,251

Problem 2:
array(670006151,670006154,670006158)
output: 670006151,4,8

Problem 3:
array(670006151,670006154,670006161)
output: 670006151,54,61

anyone know how to get output from different arrays, I need to find a common number from start then append other elements in the above problems 670006 is common in all this can be any number…

Advertisement

Answer

One way to do this is to divide each of the numbers by increasing powers of 10, stopping when the result is the same for each of them. Then subtract that result multiplied by the power from the 2nd to last entries in the array:

function common_parts($data) {
    for ($b = 1; ; $b *= 10) {
        $base = intdiv($data[0], $b);
        $matches = array_filter($data, function ($v) use ($b, $base) { return intdiv($v, $b) != $base; });
        if (count($matches) == 0) break;
    }
    $base *= $b;
    for ($i = 1; $i < count($data); $i++) {
        $data[$i] = $data[$i] - $base;
    }
    return $data;
}

print_r(common_parts(array(670006151,670006152,670006251)));
print_r(common_parts(array(670006151,670006154,670006158)));
print_r(common_parts(array(670006151,670006154,670006161)));

Output:

Array
(
    [0] => 670006151
    [1] => 152
    [2] => 251
)
Array
(
    [0] => 670006151
    [1] => 4
    [2] => 8
)
Array
(
    [0] => 670006151
    [1] => 54
    [2] => 61
)

Demo on 3v4l.org

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement