Search code examples
phpyii2session-variables

Store $_POST in Yii2 session


I'm having a little trouble with my quiz form. I'm using a page to show a single question that a user answers, from there I was hoping to save the question id and option id (My form is multiple choice, i set the options).

My HTML looks like this:

<input type="radio" name="question[3]" value="4">My Answer

When the form is posted I am doing this

if(isset(Yii::$app->session['question'])){

                // Get posted array
                $question = $_POST['question'];
                Yii::$app->session['question'] = $question;
                print_r(Yii::$app->session['question']);
            }

So it's saved into my session as:

Array
(
[3] => 4
)

Which is fine, the problem I'm finding is trying to save the next question without overwriting the previous [question_id] => [option_id].

I understand why the following code just overwrites the existing the session['question'] variable. But I'm struggling to be able to save each question and answer array to my variable.

I have tried Yii::$app->session['question'][$i] = $question; and get Indirect modification of overloaded element of yii\web\Session has no effect

I've also tried array_push and array_merge to try and combine the previous array of question and chosen option, but have had no luck either. What am I doing wrong here please?


Solution

  • The correct way to do this is

    $q = $_POST['question'];
    Yii::$app->session['question'] = array_merge(Yii::$app->session['question'], [$question]);