0

I know the title is not describing the problem very well, so I explain here: I have multiple $_POST with similar names, like question1,question2,question3...

I have a for loop with $i. i want to get this vars ($question1, $question2), in help with $i. For example:

$question.$i = $_POST['question' . $i];

I want to do it because the number of questions is variable, so I have a button that add questions and answers to the page and then you submit it.

Dushyant Joshi
  • 3,672
  • 3
  • 28
  • 52
Sergio
  • 191
  • 9

3 Answers3

1

First, you need to make explicitly $question an array. Then you build your $_POST index by concatenating the string and $i with a ..

So, before the loop:

$question = array();

and in the loop:

$question[$i] = $_POST['question'.$i];
Mat M
  • 1,786
  • 24
  • 30
DocRattie
  • 1,392
  • 2
  • 13
  • 27
1

If you don't want an array in your loop, this should fit:

${'question' . $i} = $_POST['question'.$i];

When $i=1, this will get you a $question1 variable filled with then content of $_POST['question1'].

See also Dynamic variable names in PHP which adds insight on the problem.

Community
  • 1
  • 1
Mat M
  • 1,786
  • 24
  • 30
0
 $question = array();   
 $question[] = $_POST['question'.$i];

Use array to get your values.

Muhammad Ahmed
  • 481
  • 2
  • 14