0

how do i create variable variables inside a for loop?

this is the loop:

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

}

inside this loop i would like to create a variable $seat for each time it passes but it has to incrementlike so. first time it passes it should be $seat1 = $_POST['seat'+$aantalZitjesBestellen], next time it passes: $seat2 = $_POST['seat'+$aantalZitjesBestellen] and so on.

so at the end it should be:

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

and so on.

so the variable and the content of the $_POST should be dynamic.

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
vincent
  • 2,715
  • 3
  • 17
  • 9
  • 9
    Why not make an array? – kennytm Aug 24 '10 at 09:22
  • Really you should be changing the values in $_POST variables. Are you doing this because you want to update values on a form you are displaying? If this is the case you might want to consider using javascript for this. – PhoebeB Aug 24 '10 at 09:25

5 Answers5

6

Firstly, I would use an array for this unless I'm missing something. Having variables like $seat1, $seat2, etc tends to have far less utility and be far more cumbersome than using an array.

That being said, use this syntax:

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

Lastly, PHP has an inbuilt function for extracting array keys into the symbol table: extract(). extract() has enormous potential security problems if you use it with unfiltered user input (eg $_POST) so use with caution.

cletus
  • 616,129
  • 168
  • 910
  • 942
3

This will work as well:

for ( $counter = 1; $counter <= $aantalZitjesBestellen; $counter ++) {
    ${'seat' . $counter} = $_POST['seat' . $counter];
}
nubbel
  • 1,552
  • 17
  • 24
2

(Expanded for clarity - you may be able to do a one-liner)

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

BUT! You really shouldn't do this. (And if you really must, see cletus' answer for the built-in PHP way to do it - this is considered bad practice too, though.)

Reconsider your problem and see if arrays might be the solution (I guess it will). This will make both inspection (via e.g. var_dump()) and iteration easier and does not pollute the global variable space.

Community
  • 1
  • 1
jensgram
  • 31,109
  • 6
  • 81
  • 98
0
for ( $counter = 1; $counter <= $aantalZitjesBestellen; $counter ++) {
   $name = 'seat' . $counter;
   $$name = $_POST['seat' . $counter];
}

It's recommended to use arrays, as you can check them easier.

Lekensteyn
  • 64,486
  • 22
  • 159
  • 192
0

You can use extract but I don't recommended to do what you are trying to do.

mathk
  • 7,973
  • 6
  • 45
  • 74