Page 1 of 1

How to iterate through variables?

Posted: Sun Apr 29, 2012 12:23 pm
by Vacman
OK - tricky to explain....

Compiling hockey stats and I want to figure what player got the game winning goal for that game.
Example: Final score is (Home)5 - (Away)3. The game winning goal is the 4th goal scored by the Home team. That is the goal that put them ahead of the Away team.

I have a set of variables ($h_goal_1, $h_goal_2, $h_goal_3, $h_goal_4, and $h_goal_5). So the variable $h_goal_4 would be the game winner's ID.

Here is the code I have so far:

Code: Select all

        if($home_score > $away_score){
           if($home_score - $away_score == 1){
              $h_gwg = $home_score;
           }else{
              $h_gwg = $home_score - $away_score - 1;
           }
        }
This will return a value (in this example) of 4.
What I can't figure out is how to step through the variables to get to that $h_goal_4, or how to select that particular variable and return its value.

I am sure I am having a brain fart and the answer is probably obvious, but can anyone help me muddle through it?

Re: How to iterate through variables?

Posted: Sun Apr 29, 2012 1:07 pm
by Christopher
You can iterate through them like this:

Code: Select all

for ($i=1; $i<=$score; ++$i) {
     $h_goal = "h_goal_$i";
     if ($$h_goal > $somevalue) {
          // do something
     }
}
It might be better to find change your code to put the values into an array.

Re: How to iterate through variables?

Posted: Sun Apr 29, 2012 10:51 pm
by Vacman
Hmm - Still no good. Somehow I need to be able to only retrieve the data from that Game Winning Goal variable. The code you showed essentially does the same thing mine does.

I need to be able to somehow tell the code to extract the data from that variable... will keep working - and if anyone else has an idea - let me know!

Re: How to iterate through variables?

Posted: Mon Apr 30, 2012 10:32 am
by x_mutatis_mutandis_x
Vacman wrote:Hmm - Still no good. Somehow I need to be able to only retrieve the data from that Game Winning Goal variable. The code you showed essentially does the same thing mine does.

I need to be able to somehow tell the code to extract the data from that variable... will keep working - and if anyone else has an idea - let me know!
If you want the first goal number that put the winning team ahead, then this should suffice:

Code: Select all

if ($home_score == $away_score) {
     $h_gwg = 0;
} else if ($home_score > $away_score) {
     $h_gwg = $away_score + 1;
} else {
    $h_gwg = $home_score + 1;
}

Re: How to iterate through variables?

Posted: Mon Apr 30, 2012 3:08 pm
by pickle
+1 for putting this stuff in an array. If that's impossible, what you're basically wanting is "variable variables". Google that & you should get some good info.