Home » Php » How to get $_POST and $_FILES requests with same loop in PHP

How to get $_POST and $_FILES requests with same loop in PHP

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have quiz application. where questions and answers adding dynamically with add more button. so I have no number of questions and number of answers for each questions. every questions have image, also every answers have image. I want to get every post and files request with foreach loop. I can’t use for loop because I do not know every questions/answers key in array. reason why array key is not known is that maybe user add 5 questions dynamically and then delete 3th and 4th question array keys will be 0,1,4.

in this code problem is undefined offset 1

for ($i=1; $i<count($_POST['questions'])+1 ; $i++) {

        echo'<pre>';
        echo ($_POST['questions'][$i]['question_en']);
        var_dump($_FILES['questions']['tmp_name'][$i]['image_en']);
        echo '<br>';
        for($j=1;$j<count($_POST['questions'][$i]['answers'])+1;$j++){
            echo $_POST['questions'][$i]['answers'][$j]['title_en'];
            var_dump($_FILES['questions']['tmp_name'][$i]['answers'][$j]['image_en']);

        }
        echo '</pre>';

     } 

enter image description here

How to&Answers:

If the keys of the images are the same of the questions, it might be se solution for you:

foreach( $_POST['questions'] as $question_key => $question ) {
  echo'<pre>';
  echo ($question['question_en']);
  var_dump($_FILES['questions']['tmp_name'][$question_key]['image_en']);
  echo '<br>';
  foreach( $question['answers'] as $answer_key => $answer )  {
    echo $answer['title_en'];
    var_dump($_FILES['questions']['tmp_name'][$question_key]['answers'][$answer_key]['image_en']);
  }
  echo '</pre>';
}