2

I have a nested foreach loop going through 2 arrays with a conditional if - else. When if returns a value the else statement is also still running, why is that?

//$global_plugins is an array
//$xml_plugins is a string

foreach($global_plugins as $key => $global_plugins){
  foreach ((array) $xml_plugins as $key2 => $xml_plugins){

  if (($global_plugins == $xml_plugins) && ($plugin_verso[$key] == $xml_plugin_version[$key2])){ 

       echo 'Exact match'; 

  }else{

        echo 'Fuzzy match';

    }

  }

}

For this example the array has 10 values to match, when the if returns an "Exact match" it should not also return "Fuzzy match", yet this is what is happening.

For 1 matching value I get the echo output: "Exact match" one time and "Fuzzy match" x 10

Wyck
  • 2,023
  • 4
  • 28
  • 34

2 Answers2

2

You should break the loops using the break statement.

foreach($global_plugins as $key => $global_plugins){
  foreach ((array) $xml_plugins as $key2 => $xml_plugins){

  if (($global_plugins == $xml_plugins) && ($plugin_verso[$key] == $xml_plugin_version[$key2])){ 

       echo 'Exact match'; 
       break 2;

  }else{

        echo 'Fuzzy match';
    }

  }

}
Emil Vikström
  • 90,431
  • 16
  • 141
  • 175
1

The foreach loops will iterate over all the elements, echoing either 'Exact Match' or 'Fuzzy Match'. It should not echo both within one loop, so all I can think of is that the count is off (either 11 items, or only 9 echos of 'fuzzy match').

If you want 'exact match' to output one time if any exact match is found, and 'fuzzy match' to output one time if no exact match is found you will need to restructure your loops like so:

$found = 0;
foreach($global_plugins as $key => $global_plugins)
{
  foreach ((array) $xml_plugins as $key2 => $xml_plugins)
  {   
    if (($global_plugins == $xml_plugins) && ($plugin_verso[$key] == $xml_plugin_version[$key2]))
    {    
       echo 'Exact match'; 
       $found = 1;
       break 2; // Once a match is found we exit both loops
    }
  }          
}
if ( ! $found)
{
  echo 'Fuzzy match'; // this will only be executed if no match is found
}
jisaacstone
  • 4,234
  • 2
  • 25
  • 39