php - Codeigniter, array in session, change the value of array in session in a specific key

Solution:

Two ways around your problem:

$this->session->set_userdata('slots_id'[19], 100); is not attempting to assign a value of 100 to the array element on index 19 for the $slots_id array. It's trying to set a value of 100 as the 20th character (index 19) of the 'slots_id' string, which goes out of bounds.

You may try: $this->session->set_userdata('slots_id[19]', 100);

Or even better, remove the full element from session, update it and reset it:

$aux = $this->session->userdata('slots_id');
$aux[19] = 100;
$this->session->unset_userdata('slots_id');
$this->session->set_userdata('slots_id', $aux);

it's a bit more code, but my advice would be to always replace session data rather than update it on the fly.

Answer

Solution:

Uninitialized string offset errors in PHP have a vast amount of documentation around them. You are getting this error because you are not referencing index 19 of an Array, you're referencing it of a string, which is exactly what 'slots_id' is in this instance. 'slots_id' is 8 characters long which means any index beyond 7 is in fact undefined.

If you have no direct access to the $_SESSION superglobal for some odd reason, you need to retrieve the entire slots_id array via the helper, update the index you need in your local copy, then update the session variable's slots_id array with your updated copy.

Source