1

Here is my session array:

Array ( [username] => dog@dog.net [tmpPayment] => Array ( [mID] => 48 [item_1_amt] => 35.00 [description] => Student ) ) 

I created the ['tmpPayment'] array with the following code:

$tmpPayArr = array();
$tmpPayArr = array('mID'=>$mID,'item_1_amt'=>'35','description'=>'student');
$_SESSION['tmpPayment'] = $tmpPayArr;

I have looked for a simple answer to three questions: (1)how do I add a variable to the [tmpPayment] array (2)how do I change the value of [amount] variable within the [tmpPayment] array (3)how do I remove/delete the [tmpPayment] array altogether. (4)how do I assign the value of ['tmpPayment']['mID'] to a new variable $memberID. For (3) I have unsuccessfully tried:

unset($_SESSION['tmpPayment']);

I think my main problem is not understanding how to REFERENCE the array and its variables properly.

UPDATE: I have successfully added and change my SESSION variable with the following:

$_SESSION['tmpPayment']['item_1_amt'] = $x_amount;
$_SESSION['tmpPayment']['description'] = $x_invoice_num;

Is this best practice? Still need help with (3)...removing the session variable ['tmpPayment'] from the above session array.

Leslie
  • 107
  • 1
  • 10

2 Answers2

1

Here are the answers. If they aren't working, be sure you're calling session_start(); before you try to modify the $_SESSION array.

  1. $_SESSION['tmpPayment']['new_key_name'] = 'new value';
  2. $_SESSION['tmpPayment']['item_1_amt'] = 12324;
  3. unset($_SESSION['tmpPayment']);
sa289
  • 700
  • 3
  • 12
  • QUESTION: why when I use the following code and refresh my page: `` THE SESSION IS REMOVED. My objective is to make sure that if a user leaves the page that their payment choices are reset. – Leslie Jan 15 '16 at 13:52
  • @Leslie start commenting out code piece by piece until you figure out what's causing it to not work. Special focus can be given to functions that start with "session_" if there are any. – sa289 Jan 15 '16 at 16:10
1

1: $_SESSION["tmpPayment"]["newVariable"] = "value";

2: $_SESSION["tmpPayment"]["amount"] = "$1.78";

3: To do this, you can set ["tmpPayment"] to an empty array like so: $_SESSION["tmpPayment"] = array();

or set it to null

$_SESSION["tmpPayment"] = null;

I borrowed a bit from this answer: PHP $_SESSION variable will not unset

and as that answer, and the other poster on this question mention, make sure to call session_start(); before doing anything with the session variables.

Community
  • 1
  • 1
Chris Trudeau
  • 1,427
  • 3
  • 16
  • 20