stkmedia stkmedia - 1 year ago 81
PHP Question

more efficient way to check 2 array foreach values

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';

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download