How to use if…else statement inside a foreach loop?

Ok im using this foreach loop to parse xml to add result data into my database I need to set the $win value but it always return 3 when it shouldnt b..

$myinfo = simplexml_load_file('http://mysite/results.xml'); 

foreach ($myinfo->Event as $info): 

$cid=$info['EventID']; 
$a=$info->Match['AScoreNT'];
$b=$info->Match['BScoreNT'];

if($a > $b){ 
   $win =1;
} elseif($a < $b){ 
   $win =2;
} else{ 
   $win =3;
}

$sql = "
        INSERT IGNORE INTO `engine4_event_wins`
SET `win_result` = $win,
`comp_id` = $cid;

    ";


    mysql_query($sql);

endforeach; 


<MyFeed>
<Event Sport="AFL" Description="AFL - Finals - Week 1" EventID="651239"    FinalDate="2012-09-07T00:00:00">
<Match TeamA="Hawthorn" TeamB="Collingwood" AScoreNT="135" BScoreNT="97"/>
</Event>
<Event Sport="AFL" Description="AFL - Finals - Week 1" EventID="651240"  FinalDate="2012-09-08T00:00:00">
<Match TeamA="Adelaide Crows" TeamB="Sydney Swans" AScoreNT="42" BScoreNT="71"/>
</Event>

</MyFeed>

Answers


echo the values of $a and $b and see why it's always equals :)

Another thing you can do is:

foreach ($myinfo->Event as $info): 

$a=$info->Match['AScoreNT'];
$b=$info->Match['BScoreNT'];

if($a === $b){ 
   $win =3;
elseif($a > $b){ 
   $win =1;
} elseif($a < $b){ 
   $win =2;
} else{ 
   $win =4;
}

echo $win;

endforeach; 

My guess is that it'll print 4...

Update: My suspicious was correct, you're comparing strings instead of ints, that's why you get the equal result (both sides are not empty strings, hence, according to PHP - they are similar... I know, it's not intuitive, I recommend reading about it!).

In order to fix it, change your code to:

if((int)$a > (int)$b){ 
   $win =1;
} elseif((int)$a < (int)$b){ 
   $win =2;
} else{ 
   $win =3;
}

I just added str_replace before if statement and is working perfect now.. that remembers me the parsefloat in javascript.. very rare but solved the issue.. thanks guys


    $a = str_replace( ' ', '', $a ); 
    $b = str_replace( ' ', '', $b );


Need Your Help

Compare files in List<FileInfo> using LINQ C#

c# linq list file compare

I have 2 collections of files as List&lt;FileInfo&gt;. I am currently using 2 x foreach to loop through each set and match the files (shown below). Is there a quicker way to do this in LINQ and .Re...

How stable are multiple instances of R when one instance is running an external program?

r multiple-instances

I am running an external program via R that is pretty memory hungry and can take >8 hours to run. I'd like to open up another instance of R to do other tasks but am concerned about crashing the ex...