Tarang Panchal Tarang Panchal - 3 years ago 127
PHP Question

Add value to associative array that store in session

include('session.php');

$productname = $_GET['productname'];
$productcode = $_GET['productcode'];

$wishlist = array("$productname" => $productcode);

$_SESSION["wishlist"] = $wishlist;

print_r($_SESSION["wishlist"]);


This code set as an array to a session named "wishlist".

The problem is that the session is being replaced. I want to add to the array if it already exists.

So how can I update my array with new data.
I have tried the following.

$productname = $_GET['productname'];
$productcode = $_GET['productcode'];
$lastsession = $_SESSION["wishlist"];

// CHECK IF SESSION IS EMPTY OR NOT
if(empty($lastsession)) {
$wishlist = array("$productname" => $productcode);
} else {
/*
How Can I Update array ???
*/
}


The array output is like so. It is associated not numeric indexed.
And i want result in single array. Not array in array.

[mobile] => iphone_2


Thank you.

Answer Source

In short, you can do this (if I understand the question correctly):

$productname = $_GET['productname'];
$productcode = $_GET['productcode'];
$lastsession = $_SESSION["wishlist"];

// CHECK IF SESSION IS EMPTY OR NOT
if(empty($lastsession)) {
    $wishlist = array("$productname" => $productcode);
} else {
    array_push($wishlist, array("$productname" => $productcode));
}

array_push is a function that will add information to the end of an array. In this instance, we are using it to add the product array to the current wishlist.

An alternative simple solution would be:

// create a blank array if the session variable is not created
// array_push requires an array to be passed as the first parameter
$wishlist = isset($_SESSION["wishlist"]) ? $_SESSION["wishlist"] : array();
//$wishlist = $_SESSION["wishlist"] ?? array(); // this is for PHP 7+
array_push($wishlist, array("$productname" => $productcode));

// you can then access each product as:
$wishlist["mobile"];

Or replace line 5 from the above code snippet with the following:

$wishlist[$productname] = $productcode;

This would save you from creating an empty array as in line 3. The advantage that array_push has over this is that you can add multiple products at once such as:

$products = [$productname1 => $productcode1, $productname2 => $productcode2];
array_push($wishlist, $products);

The one thing I have noticed is that you are setting the session to $lastsession as well as using $wishlist. Try and keep duplicate variables to non-existent.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download