Variable variables

how to create variable variables inside a for loop?

this is a loop:

for ( $counter = 1; $counter <= $aantalZitjesBestellen; $counter ++) {

}

inside this loop, I would like to create the $ seat variable every time it passes, but it should increase like this. the first time it should be $seat1 = $_POST['seat'+$aantalZitjesBestellen], the next time: $seat2 = $_POST['seat'+$aantalZitjesBestellen]etc.

so at the end it should be:

$seat1 = $_POST['seat1'];
$seat2 = $_POST['seat2'];

etc.

therefore, the variable and the contents of the variable $ _POST must be dynamic.

0
source share
5 answers

Firstly, I would use an array for this if I did not miss something. Having type variables $seat1, $seat2etc., tends to be of much less utility and much more cumbersome than using an array.

Use this syntax:

for ( $counter = 1; $counter <= $aantalZitjesBestellen; $counter ++) {
  $key = 'seat' . $counter;
  $$key = $_POST[$key];
}

, PHP : extract(). extract() , (, $_POST), .

+6

:

for ( $counter = 1; $counter <= $aantalZitjesBestellen; $counter ++) {
    ${'seat' . $counter} = $_POST['seat' . $counter];
}
+3

( - )

for ( $counter = 1; $counter <= $aantalZitjesBestellen; $counter ++) {
    $varname = 'seat' . $counter;
    $$varname = $POST[$varname];
}

! . ( , . cletus ' PHP, - .)

Review your problem and see if arrays can be a solution (I think it will). This will simplify checking (through var_dump()) and iteration and not pollute the global space of variables.

+2
source
for ( $counter = 1; $counter <= $aantalZitjesBestellen; $counter ++) {
   $name = 'seat' . $counter;
   $$name = $_POST['seat' . $counter];
}

It is recommended to use arrays, as you can check them more easily.

0
source

You can use extract , but I do not recommend doing what you are trying to do.

0
source

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


All Articles