0

Is there a more efficient way to foreach check an array for similar values against multiple arrays? Here's my code:

foreach ($city as $option) {
    if (in_array($option, $optionarray1)) {
        $tables[] = 'newvalue1';
    } else if (in_array($option, $optionarray2)) {
        $tables[] = 'newvalue2';
    } else if (in_array($option, $optionarray3)) {
        $tables[] = 'newvalue3';
    }
 }
1
  • 1
    given you're adding different values for each comparison, no... not really. Commented Sep 14, 2016 at 21:35

1 Answer 1

1

Use array_flip() to turn each $optionarrayX into an associative array, so you don't have to do linear searches each time.

$optionhash1 = array_flip($optionarray1);
$optionhash2 = array_flip($optionarray2);
$optionhash3 = array_flip($optionarray3);

Then you can put these all in an array, so you can use a nested loop instead of repeating code.

$optionhashes = array(1=>$optionhash1, 2=>$optionhash2, 3=>$optionhash3);

foreach ($city as $option) {
    foreach ($optionhashes as $i => $hash) {
        if (array_key_exists($option, $hash)) {
            $tables[]= 'newvalue' . $i;
            break;
        }
    }
}
Sign up to request clarification or add additional context in comments.

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.