Leslie
Leslie

Reputation: 107

accessing session array data, deleting or changing one of the variables within this array

Here is my session array:

Array ( [username] => [email protected] [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.

Upvotes: 1

Views: 53

Answers (2)

Chris Trudeau
Chris Trudeau

Reputation: 1437

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.

Upvotes: 1

sa289
sa289

Reputation: 700

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']);

Upvotes: 1

Related Questions