dsfsw1233 2016-08-10 11:00
浏览 218
已采纳

如何在foreach循环中创建变量并在循环外使用它?

I'm comparing 2 numbers entered to numbers in an xml file and then storing the result of each comparison in a variable ($n1, $n2). I'm then adding the total of each variable up and storing it in a new variable $total within the foreach loop. I've tried displaying the result in the loop but it shows both the result for correct and incorrect comparison as it loops around the whole xml.

I want to be able to use $total outside of the loop to display a result. When I echo $total outside the loop, its result is 0 no matter whether the comparisons are correct. When I echo it in the loop it has a value.

How to I ensure the $total variable keeps its stored value outside of the loop?

$num1 = $_POST['num1'];
$num2 = $_POST['num2'];

$xml = simplexml_load_file('lottery2.xml') or die("Error: Cannot create object");
if(isset($_POST['num1'])&& isset($_POST['num2']))
{
foreach($xml->children() as $record)
{ 
    if($record->num1 == $num1 || $record->num2 == $num1) 
     {
        $n1=1;
     } 
    else 
     {
        $n1=0;
     }
    if($record->num1 == $num2 || $record->num2 == $num2) 
     {
        $n2=1;
     } 
    else 
     {
        $n2=0;
     }

    $total= $n1+$n2;

}//end foreach

    if ($total=2) {
        echo "Jackpot is ".$record->jackpot ."<br />";
    } else {
        echo "No jackpot, sorry";
    }
  • 写回答

3条回答 默认 最新

  • dryk50495 2016-08-10 11:02
    关注

    If all you care about is whether both numbers were found, use booleans (no need for $total):

    $n1 = false;//make true once we find 1st num
    $n2 = false;//make true once we find 2nd num
    foreach($xml->children() as $record){
        $n1 = $n1 || $record->num1 == $num1 || $record->num2 == $num1;
        $n2 = $n2 || $record->num1 == $num2 || $record->num2 == $num2;
    
        if($n1 && $n2) break; //we've found both. No need to keep looking
    }//end foreach
    
    if ($n1 && $n2) echo "Jackpot!";
    else echo "No Jackpot, sorry";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?