开发者

Array copying in PHP

开发者 https://www.devze.com 2023-03-29 19:33 出处:网络
I am trying to save my _POST array to a _SESSION array so that I can use that in other pages of the website

I am trying to save my _POST array to a _SESSION array so that I can use that in other pages of the website when i do

$_SESSION = $_POST;

it didn't worked.开发者_如何学运维

Also the following code also is giving a error and not copying it.

foreach($_POST as $element){
  $_SESSION[] = $element;
}


$_SESSION can't handle numeric keys; it must be an associative array. I.e. if you do

$_SESSION[] = "foo";

like you do in your foreach-loop, it'll create a new numeric key like in any other array (e.g. $_SESSION[0] == "foo"), but PHP will skip the key when saving the session. You get an "notice"-level warning like "Skipping numeric key 0". So the next time the $_SESSION array is read, it won't contain any numeric keys.

So you must use a string index, like:

$_SESSION['POST'] = $_POST;

That should work.

You should also be able to do $_SESSION = $_POST and overwrite the entire $_SESSION array. Can't say why that doesn't work. But I can't see why you would want to do it either. If you ever want to use $_SESSION for anything else (like, actual session data), you can't have your code randomly overwriting the entire array with post data here and there. Better to just use a string index like above to store the post data.


session_start();

if(!$_SESSION['POST']) $_SESSION['POST'] = array();

foreach ($_POST as $key => $value) {
    $_SESSION['POST'][$key] = $value;
}

var_dump($_SESSION['POST']);
0

精彩评论

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