user2417624 user2417624 - 3 months ago 8
PHP Question

Comparing if value from one array exist in another with use of string comparing functions

I have 2 comma separated values, which I convert in 2 arrays, named:
$companyCad and $programCad

Those 2 arrays return values in the following format:

$companyCad

Array
(
[0] => 52.10
[1] => 62
[2] => 64.15.44.25
[3] => 65.10
[4] => 65.14
[5] => 65.21
[6] => 70
[7] => 71
[8] => 71.15.12
[9] => 93.55
)


$programCad

Array
(
[0] => 92.55
[1] => 92.74
[2] => 93
[3] => 94.10
[4] => 98.12
[5] => 98.66
)


To compare if any of the
$companyCad
values exist in the
$programCad
I use the following code:

if (array_intersect($companyCad, $programCad)) {
echo "Found";
} else {
echo "Not found";
}


Above code return not found since 93.55 from
$programCad
is not found in the array
$companyCad
. I know that the code works just fine.

However I need partial match, that is:

If the value of the
$companyCad
is longer than value of the
$programCad
for example
$companyCad[9] = 93.55
and the
$programCad[2] = 93
that should be considered as match.

If the
$companyCad[9] = 93.55
and the
$programCad[2] = 93.1
it should not be considered as match however.

If the
$companyCad[9] = 93.5X
and
the $programCad[2] = 93.5
it should be considered as match also. (X = any number)

Here are some more explanations of eventual format of the array values:

Array value will have at least 2 digits = XX
The shortest value may be XX while the longest is XX.XX.XX.XX
However it may end with 1 digit in some cases, example XX.X or XX.XX.X for example.

Any idea how can I do this partial match?

Answer

One way to accomplish it is using nested loops and strpos to look if the haystack (value from first loop) starts with the needle (value from second loop).

$companyCad = array("52.10", "62", "64.15.44.25", "65.10", "65.14", "65.21", "70", "71", "71.15.12", "93.55");
$programCad = array("92.55", "92.74", "93", "94.10", "98.12", "98.66", "71.1");

$found = false;
foreach($companyCad as $comp) {
    foreach($programCad as $prog) {
        if(strpos($comp, $prog) === 0) {
            $found = true;
            break;
        }
    }
}

if($found === true) {
    echo "Found";
} else {
    echo "Not Found";
}

Live demo

Comments