Php for loop variable names

I got code 100-200 rules for creating a table. but the same thing happens all the time. I got the variable $ xm3, then I create a column. the next row, I got $ xm2 and make a column. the next row, I got $ xm1 and make a column.

so my variables go to $ xm3, $ xm2, $ xm1, $ xm0, $ xp1, $ xp2, $ xp3.

Is there a way to make forloop so that I can populate $ xm and then the value from the for loop?

+3
source share
5 answers

In such a structure, you'd better use an array for these 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.

}
+3
source

, ,

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

PHP, . ( , . .)

+2

, .

, ,

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

$xm[] = "";

a :

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

: Googled, , . !

+1

, , .

, , "y" - for:

${'xm' . $y} = $someValue;
0

- :

$base_variable = 'xm';

, ; :

for ($i=0; $i<10; $i++)
{
  $def_variable = $base_variable . $i;
  $$def_variable = 'value'; //this is equivalent to $xm0 = 'value'
}
0

Source: https://habr.com/ru/post/1747396/


All Articles