How do I do this in Yii2

I’m having a time trying to do this. I’ll be honest I’ve never used sessions a lot. But as far as I understand you should be able to do this in PHP (As long as you’ve set the session variable to an array.

$question = $_POST['question'];

$_SESSION['question'][] = $question;

When I do this in Yii2

$question = $_POST['question'];

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

I get: Indirect modification of overloaded element of yii\web\Session has no effect

What am I doing wrong here. I am trying the save an array of arrays here. My $_POST[‘question’] is array([4] => 7) to represent question number 4 and answer number 7. I plan to save all the question and answer pairs into a single session variable

Anyone who could point me on the right track would be great

You can not use the session to modify the array directly beacuse PHPs internal magic with ArrayAccess does not support this.

You have to make it a bit less nice:

$question = $_POST['question'];

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

Thanks Cebe!