Foreach loop repetition problem
This code gives four 4's and I only want one 4.. Can anyone 开发者_运维百科identify the problem??
$value1 = "0";
$entries = array($var1_1a>$var1_1b, $var1_2a>$var1_2b, $var1_3a>$var1_3b,
$var3_1a>$var3_1b, $var3_2a>$var3_2b, $var3_3a>$var3_3b);
if (count($entries) == 0)
echo "0";
else foreach($entries as $entry)
{
if($entry > $value1)
{
echo array_sum($entries);
}
}
Why do you even have a foreach loop? echo array_sum($entries);
is independent of the values you're looping through.
This should be adequate:
$entries = array($var1_1a>$var1_1b, $var1_2a>$var1_2b, $var1_3a>$var1_3b,
$var3_1a>$var3_1b, $var3_2a>$var3_2b, $var3_3a>$var3_3b);
echo array_sum($entries);
$value1 = "0";
$entries = array($var1_1a>$var1_1b, $var1_2a>$var1_2b, $var1_3a>$var1_3b,
$var3_1a>$var3_1b, $var3_2a>$var3_2b, $var3_3a>$var3_3b);
if (count($entries) == 0)
echo "0";
else foreach($entries as $entry)
{
if($entry > $value1)
{
echo array_sum($entries);
break; //I think it will checking condition repeatedly
}
}
精彩评论