1

I've two A and B arrays, first one (A) is simple array where as the second one (B) is array of arrays. I want to find whether some element in A is equal to element in B. For doing this I'm currently doing nested loops which results in n^3 complexity. How can I improve upon this.

for ($i = 0; $i <= count($A); $i++) {
    if (isset($A[$i])) {
        foreach ($B as $items) {
            foreach ($items as $item) {
                if ($item['Column1'] == $A[$i]['Column1']) {
                    array_push(A, "result");
                    unset($A[$i]);
                    unset($items);
                    break;
                }
            }
        }
    }
}
1
  • 1
    Please, provide arrays examples and whanted result. Commented Jul 8, 2013 at 9:13

3 Answers 3

2
array_walk_recursive($B, function($val) {
  if (in_array($val, $A)) echo "$val is in the \$A array!";
});
Sign up to request clarification or add additional context in comments.

1 Comment

a simple in_array cannot work, the $B array is multidimensional
1

Try this, array_seacrh() will remove your one foreach loop :

for ($i = 0; $i <= count($A); $i++) {
    if (isset($A[$i])) {
        foreach ($B as $items) {
            $t = array_search($A[$i]['Column1'], $items);
            array_push($A, "result");
            unset($A[$i]);
            unset($items[$t]);
        }
    }
}

Comments

0

when creating your arrays you can create a $lookup_A and $lookup_B arrays, where the keys are the values from the original $A and $B

Then you can do a simple loop on $lookup_A and check for if (isset($lookup_B[$lookup_A_key]))

Also in your example if(isset($A[$i])) is always true i think

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.