简体   繁体   中英

How to use a variable in an array request in php

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?

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.

You can try this:

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

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.

Include the $i at the end of the string :

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

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++;
}

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++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM