Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

singh's avatar
Level 1

How to capture and process inputs from a dynamically generated form

Looking for some advice on how to capture and process inputs from a dynamically generated form. Use Case:

  1. Teacher A uploads an assignment text file with 5 questions that students must submit answers to online.
  2. Teacher B uploads an assignment text file with 7 questions that students must submit answers to online.
  3. Teacher C uploads an assignment text file with 8 questions that students must submit answers to online.
  4. Teacher D uploads an assignment text file with 2 questions that students must submit answers to online.

The number of questions can vary when these teachers give another assignment the next time.

For each assignment students will see a form that has questions and a text box below each question that students must fill.

The creation of the form is probably easily as I can assign the input id by joining the word question_ and the id for the question stored in the database.

My question is - How would the input controller store these questions and answer. For example,

$question1 = $request->question1; $question2 = $request->question2;

But in this case it could be any number of variables.

0 likes
2 replies
LaryAI's avatar
Level 58

You can use a loop to capture the inputs from the dynamically generated form. For example, you can use a foreach loop to loop through the form inputs and store them in an array. Then you can use the array_values function to get the values from the array and store them in variables.

$inputs = array();
foreach($_POST as $key => $value) {
    $inputs[$key] = $value;
}

list($question1, $question2, ...) = array_values($inputs);

You can also use the extract function to extract the values from the array and store them in variables.

$inputs = array();
foreach($_POST as $key => $value) {
    $inputs[$key] = $value;
}

extract($inputs);
tisuchi's avatar

@singh How about this way?

$inputs = $request->all();

$answers = [];

foreach ($inputs as $inputKey => $inputValue) {
    if (strpos($inputKey, 'question_') !== false) {
        $questionId = str_replace('question_', '', $inputKey);
        $answers[$questionId] = $inputValue;
    }
}

// Now you have an array of answers, you can store them in the database

Please or to participate in this conversation.