Appending Data To Existing CodeIgniter Session Variable
When storing information in a session, it is likely that you may want to add additional inormation to this session at a later date. For this particular post I’ll be focusing on how to achieve this within CodeIgniter. Allow me therefore to first demonstrate how the session we will be extending may be getting initialised in the first place:
$data = array( 'username' => 'joebloggs', 'name' => 'Joe Bloggs', 'email' => 'firstname.lastname@example.org' ); $this->session->set_userdata('user', $data);
In the above code we are creating a session called ‘user’, then assigning an array to it containing the users information.
Now, lets imagine that at a later date we also want to add a phone number to this session. We can do this easily using the method outlined below:
$data = $this->session->userdata('user'); $data['telno'] = "01234 567 890"; $this->session->set_userdata('user', $data);
If you can’t make out what we’re doing here, we’re assigning the existing user data to a variable called $data. We then add an extra element to the array, in our case this is the user’s telephone number, then overwrite the existing user session with the new infrmation.