0

Okay so i am trying to retrieve the object value iterating through a for loop.

Manually it looks like this:

echo $game->stats->item0;
echo $game->stats->item1;
...

I want to do it something like this:

for($i = 0; $i < 6; $i++) {
    echo $game->stats->item.$i;
}

The above however just returns the value of $i. How can i return the actual object value?

Thanks

  • You need a Variable variable. So it would be `echo $game->stats->{"item$i"};`. See http://stackoverflow.com/questions/9257505/dynamic-variable-names-in-php or http://php.net/manual/en/language.variables.variable.php – Sean Oct 12 '15 at 03:25

2 Answers2

1

Basically, your statement should be like this:

echo $game->stats->{'item'.$i}

Regards,

Dat Pham
  • 1,765
  • 15
  • 13
1

Instead of item.$i, use {"item$i"}.

for($i = 0; $i < 6; $i++) {
    echo $game->stats->{"item$i"};
}

Another way you can do it is to set a variable to be equal to 'item' . $i.

for($i = 0; $i < 6; $i++) {
    $item = 'item' . $i;
    echo $game->stats->$item;
}
Zsw
  • 3,920
  • 4
  • 29
  • 43