php for loop variable names

后端 未结 5 1428
北恋
北恋 2021-01-21 01:22

i got a code of 100-200 rules for making a table. but the whole time is happening the same. i got a variable $xm3, then i make a column . next row, i got $xm2 and make column. n

相关标签:
5条回答
  • 2021-01-21 01:44

    In this kind of structure you'd be better off using an array for these kinds of values, but if you want to make a loop to go through them:

    for($i = 0; $i <= 3; $i++) {
        $var = 'xm' . $i
        $$var; //make column stuff, first time this will be xm0, then xm1, etc.
    
    }
    
    0 讨论(0)
  • 2021-01-21 01:46

    You can do this using variable variables, but usually you're better off doing this sort of thing in an array instead.

    If you're positive you want to do it this way, and if 'y' is the value of your counter in the for loop:

    ${'xm' . $y} = $someValue;
    
    0 讨论(0)
  • 2021-01-21 01:49

    It is not fully clear what you are asking, but you can do

    $xm = 'xm3';
    $$xm // same as $xm3
    

    in PHP, so you can loop through variables with similar names. (Which does not mean you should. Using an array is usually a superior alternative.)

    0 讨论(0)
  • 2021-01-21 01:51

    You can easily do something like this:

    $base_variable = 'xm';
    

    and then you can make a loop creating on the fly the variables; for example:

    for ($i=0; $i<10; $i++)
    {
      $def_variable = $base_variable . $i;
      $$def_variable = 'value'; //this is equivalent to $xm0 = 'value'
    }
    
    0 讨论(0)
  • 2021-01-21 01:59

    As far as I am aware using different variable names is not possible.

    However if you uses arrays so as below

    $xm[3] = "";
    $xm[2] = "";
    $xm[1] = "";
    $xm[0] = "";
    

    or just $xm[] = "";

    Then you can use a for each loop:

    foreach($xm as $v) { echo $v; }
    

    Edit: Just Googled and this is possible using variable names but is considered poor practice. Learn and use arrays!

    0 讨论(0)
提交回复
热议问题