1

What is the proper way to add an array to a $_SESSION variable that already contains arrays in PHP?

For example I have a session variable:

$_SESSION['test']

Then I do this:

$_SESSION['test'] = array('sample' => '1', 'sample2' => 2);

THEN, I come back to this session data at a later date. How would I add another array to $_SESSION['test'] without destroying what was already in there?

3 Answers 3

3

Do you mean add another array element?

If so, you would do:

$_SESSION['test']['sample3'] = 3;

But if not, then it sounds like array_merge is your ticket.

Sign up to request clarification or add additional context in comments.

Comments

1

Fetch the size of current value, if it's 1 (means there is one array), then make a new array, which contains previous value from test and add the new value. Then change test value to this new two dimension array.

Would look something like that:

$_SESSION['test'] = array('sample' => '1', 'sample2' => 2);

if(is_array($_SESSION['test']) && sizeof($_SESSION['test'] == 1){
    $newValue = array();
    $newValue[] = $_SESSION['test'];
    $newValue[] = $yourOtherArray;
    $_SESSION['test'] = $newValue;
}

Fast and simple. Oh, not so sure if this is "proper" way.

3 Comments

Seems like a whole lot of extra and unnecessary work given that array_merge function. Although, testing if it is an array is probably a good idea.
But array_merge() will merge them together, where this will keep em seperated.
Yea, I get you. I guess it all depends on what the OP meant, as he was sort of unclear on that / could be taken multiple ways. It would also depend on the format of the "new array" if it is multi-dimensional or not. +1
1

If I am understanding you correctly, you can use array_merge() to merge the arrays.

$new_array = array('x' => array('extra')));
$_SESSION['test'] = is_array($_SESSION['test'])?array_merge($_SESSION['test'], $new_array):$new_array;

EDIT

Updated to do an is_array check, if it is an array it is merged, else it is set to the $new_array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.