2

Im using

$i = 0;
while ($i <= 6) {
    print $game['stats']['item0'];
    $i++;
}

I want the item0 to increment to item1 up to item6, so the last while should be
print $game['stats']['item6'];

I also tried: $game['stats']['item{$i}'] but it doesn't work.

Any Ideas for me?

6 Answers 6

2

If you need to do something a set number of times, a for loop is generally more concise than a while loop.

for ($i=0; $i < 6; $i++) {
    print $game['stats']["item$i"];
}

It isn't a more correct way of doing it, it really just depends on your style, but I thought it was worth mentioning.

Sign up to request clarification or add additional context in comments.

1 Comment

yeah you are right. I'd never used a for loop. I need to start using it i guess :) Thanks
1

You can try this:

while ($i <= 6) {
    $key = 'item'.$i;   
    print $game['stats'][$key];
    $i++;
}

1 Comment

You're welcome, mate. Please vote it up and accept the answer if it solves your purpose. :)
0

You should be good to go with this

$i = 0;
while ($i <= 6) {
    print $game['stats']["item$i"];
    $i++;
}

When a string is specified in double quotes or with heredoc, variables are parsed within it.

Comments

0

Include the $i at the end of the string :

<?php
$i = 0;
while ($i <= 6) {
    print $game['stats']['item' . $i];    //<============== , 'item0', 'item1', ...
    $i++;
}
?>

Comments

0

You have to append $i after item. And you don't need to define new variable.

$i = 0;
while ($i <= 6) {
    print $game['stats']['item'.$i];
    $i++;
}

Comments

0

Here's an edited version of your code. It should work:

<?php
$i = 1;
$game = array("stats" => 
array("item1" => 1, "item2" => 2, "item3" => 3, "item4" => 4, "item5" => 5, "item6" => 6 ));
while ($i <= 6) {
    $tmp = 'item'.$i;
    print $game['stats'][$tmp];
    $i++;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.