2

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?

Jonnny
  • 4,939
  • 11
  • 63
  • 93
  • http://stackoverflow.com/questions/25079781/how-to-add-more-user-identity-session-attributes-in-yii2 http://www.yiiframework.com/doc-2.0/yii-web-session.html – Kshitiz Oct 04 '14 at 06:09

2 Answers2

2

The correct way to do this is

$q = $_POST['question'];
Yii::$app->session['question'] = array_merge(Yii::$app->session['question'], [$question]);
Jonnny
  • 4,939
  • 11
  • 63
  • 93
1

You should do

Yii::$app->session['question'][] = $question;

Notice the extra []

Mihai P.
  • 9,307
  • 3
  • 38
  • 49