Home > OS >  Check if 2 elements exist independently in two array with special conditions
Check if 2 elements exist independently in two array with special conditions

Time:11-09

I'm trying to find if a given 2-element array ($result) exists on a dynamically created multidimentional array.

There are 2 flat arrays ($a and $b) which will be used to generate a haystack array of 2-element combinations.

$a = [1, 2, 3];
$b = [3, 4, 5];

$result = [1,3];

I want to check if the $result array exists (with the two values in either orientation) in the haystack array.

The (cross joined) haystack array ($selections) looks like the following:

[
    [1,3],
    [1,4],
    [1,5],
    [2,3],
    [2,4],
    [2,5],
    [3,4],
    [3,5]
]

Notice that [3,3] is excluded by my application's logic.

I build $selections this way:

$selections = [];
foreach($a as $s){
    foreach($b as $o){
        if($s == $o){
            continue;
        }
        $selections[] = [$s, $o];
    }
}

The $result should be considered found by the following non-exhaustive list:

  • [1, 3]
  • [3, 1]
  • [2, 5]
  • [3, 3]

But pairs like these should not be considered found:

  • [1, 2]
  • [3, 3]
  • [4, 4]

I tried using array_search(array_search($result, $selections)), but it only wwors if the elements are in order.

Of course, I can write a custom function to iterate through the multidimentional array and check the intersection, but I'm checking if there's a cleaner way to do this.

CodePudding user response:

To allow out of order rule satisfaction, just check both ways explicitly.

Code: (Demo)

var_export(
    $result[0] !== $result[1] 
    && (
        (in_array($result[0], $a) && in_array($result[1], $b))
        || (in_array($result[0], $b) && in_array($result[1], $a))
    )
);

If the first pair of in_array() calls is satisfied, then the second set will not be executed at all.

CodePudding user response:

You don't have to create every possible combination, it's quite expensive.

It is better to split the $result array and find each element in the arrays $a and $b.

<?php

$a = [1,2,3];
$b = [3,4,5];

$result = [3,1];

function isOK($a, $b, $result):bool {
    return $result[1] && in_array($result[0], $a) && in_array($result[1], $b);
}

$isOK = isOK($a, $b, $result) || isOK($a, $b, array_reverse($result));

var_dump($isOK);
  • Related