开发者

Proper way to add an array to a $_SESSION variable that already contains arrays in PHP?

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?


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜