简体   繁体   中英

How to assign an array to variable in php

I have a function with a reference parameter. The function populates the reference with an array. When it returns I test the reference value with a print_r() . It's successful. But when I try and assign it to another var as in,

$_SESSION['allvats'] = $ref_all_vats;

I get an empty session var. How do I assign this? I've tried declaring the reference as an array before invoking the function and also assigning to sessions as

$_SESSION['allvats'][] = $ref_all_vats;

Thank you.

Edit.

Session is running. Other SESSION vars populate. Here is the code bit:

    if(buildMetalArrayNsp($process_id, $ref_all_vats)) {
       writeDataToFile("vats " . print_r($ref_all_vats, true), __FILE__, __LINE__);
       $_SESSION['allvats'] = $ref_all_vats;
    }

Here is the session code:

$lifetime= 60 * 60 * 24 * 30;  // 30 days
session_start();
setcookie(session_name(),session_id(),time()+$lifetime);

Try like this

session_start();
$_SESSION['allvats'] = $ref_all_vats;
list($firstVar, $secondVar) = explode(' ', 'Foo Bar');

list()是你所追求的。

Your code is fine, there is something else going wrong. Are you sure the if statement is evaluating to true? Whenever you are tracking down errors it is good to use echo or print_r quite a bit. For example:

echo "<pre>Above if\n";
if(buildMetalArrayNsp($process_id, $ref_all_vats)) {
   echo "In if\n";
   $_SESSION['hello'] = "world";
   $_SESSION['allvats'] = $ref_all_vats;
}
echo "Below if\n";

echo "\n-----------------------\n";
echo $_SESSION['hello'];
echo "\n-----------------------\n";
print_r($_SESSION['allvats']);
echo "\n-----------------------\n";
print_r($ref_all_vats);
echo "</pre>";

Of course if you are not displaying to a web page remove the <pre> tags.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM