How to concatenate PHP variable name?

后端 未结 4 1986
抹茶落季
抹茶落季 2020-11-27 05:26

I have a PHP for loop:

for ($counter=0,$counter<=67,$counter++){

echo $counter;
$check=\"some value\";

}

What I am trying to achieve i

相关标签:
4条回答
  • 2020-11-27 06:02

    The proper syntax for variable variables is:

    ${"check" . $counter} = "some value";
    

    However, I highly discourage this. What you're trying to accomplish can most likely be solved more elegantly by using arrays. Example usage:

    // Setting values
    $check = array();
    for ($counter = 0; $counter <= 67; $counter++){
        echo $counter;
        $check[] = "some value";
    }
    
    // Iterating through the values
    foreach($check as $value) {
        echo $value;
    }
    
    0 讨论(0)
  • 2020-11-27 06:02

    You should use ${'varname'} syntax:

    for ($counter=0,$counter<=67,$counter++){
        echo $counter;
        ${'check' . $counter} ="some value";
    }
    

    this will work, but why not just use an array?

    $check[$counter] = "some value";
    
    0 讨论(0)
  • 2020-11-27 06:02

    This is usable in some cases. For example if your app has something like 2 language entries in DB.

    echo $this->{'article_title_'.$language};
    

    That's much more usable than for example this;

    if($language == 'mylanguage1')
        echo $this->article_title_mylanguage1;
    else
        echo $this->article_title_mylanguage2;
    

    Obviously this is what you should not have to do in your multilingual app, but i have seen cases like this.

    0 讨论(0)
  • 2020-11-27 06:10

    An array would accomplish this.

    $check = array();
    
    for($counter = 0; $counter <= 67; $counter++) {
        $check[] = "some value";
        var_dump($check[$counter]);
    }
    
    0 讨论(0)
提交回复
热议问题