Nested foreach if else not working

安稳与你 提交于 2020-01-05 03:24:55

问题


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


回答1:


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

  }

}



回答2:


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
}


来源:https://stackoverflow.com/questions/5930244/nested-foreach-if-else-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!