dsfsw1233
2016-08-10 11:00 阅读 123

如何在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 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";
    
    点赞 评论 复制链接分享
  • donglao6169 donglao6169 2016-08-10 11:04

    Change

    if ($total=2)
    

    to

    if ($total == 2)
    
    点赞 评论 复制链接分享
  • dtutlamjasblef7982 dtutlamjasblef7982 2016-08-10 11:08

    Declare it outside the loop

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

    and concatenate the value.

     $total+=$num1+$num2;
    
    点赞 评论 复制链接分享

相关推荐