Loop through variables with common name

前端 未结 4 1882
名媛妹妹
名媛妹妹 2020-12-19 16:44

At first glance I think you can get what I\'m trying to do. I want to loop though variables with the same name but with a numerical prefix. I also had some confusion about t

相关标签:
4条回答
  • 2020-12-19 17:13

    You can use variable variables as:

    for ( $counter = 1; $counter <= 10; $counter += 1) {
            echo ${'hello' . $counter } , '<br>';
    }
    
    0 讨论(0)
  • 2020-12-19 17:26

    as I guess u not even need to declare $hello1 = "hello1". coz the $counter is incrementing the numbers by its loop.

    <?php 
    for ( $counter = 1; $counter <= 10; $counter += 1) {
    echo 'hello' . $counter . "\n";
    }
    ?>
    

    so this is enough to get the output as you want.

    the output will be:-

    hello1
    hello2
    hello3
    hello4
    hello5
    hello6
    hello7
    etc...
    
    0 讨论(0)
  • 2020-12-19 17:27

    It's generally frowned upon, since it makes code much harder to read and follow, but you can actually use one variable's value as another variable's name:

    $foo = "bar";
    $baz = "foo";
    
    echo $$baz; // will print "bar"
    
    $foofoo = "qux";
    echo ${$baz . 'foo'}; // will print "qux"
    

    For more info, see the PHP documentation on variable Variables.

    However, as I already mentioned, this can lead to some very difficult-to-read code. Are you sure that you couldn't just use an array instead?

    $hello = array(
        "hello1",
        "hello2",
        // ... etc
    );
    
    foreach($hello as $item) {
        echo $item . "<br>";
    }
    
    0 讨论(0)
  • 2020-12-19 17:29

    Try ${"hello" . $counter}

    $a = "hell";
    $b = "o";
    $hello = "world";
    echo ${$a . $b};
    
    // output: world
    
    0 讨论(0)
提交回复
热议问题