user1780242
user1780242

Reputation: 551

Removing an array from a session array

I am building a shopping cart using session variables. I can push the array to the session array like this:

//initialize session cart array
$_SESSION['cart'] = array();
//store the stuff in an array
$items  = array($item, $qty);
//add the array to the cart
array_push($_SESSION['cart'], $items);

So far, so good. The problem is in removing an item from the cart. When I try to use this, I get a array to string conversion error.

//remove an array from the cart
$_SESSION['cart'] = array_diff($_SESSION['cart'], $items);

To clarify, the question here is why is the above statement creating an array to string conversion error?

Upvotes: 1

Views: 1134

Answers (2)

RiggsFolly
RiggsFolly

Reputation: 94652

How about storing an array of objects like this. In my opinion it is a lots easier to read the code this way than addressing arrays within arrays

$item = new stdClass();
$item->id = 99;
$item->qty = 1;
$item->descr = 'An Ice Cream';
$item->price = 23.45;

$_SESSION['cart'][$item->id] = $item;

To remove an items from the cart

unset($_SESSION['cart'][$item]);

To re-access the items data

echo $_SESSION['cart'][$item]->id;
echo $_SESSION['cart'][$item]->desc;
echo $_SESSION['cart'][$item]->price;

Or even

$item = $_SESSION['cart'][$item];
echo $item->id;
echo $item->desc;
echo $item->price;

Or even better

foreach ( $_SESSION['cart'] as $id => $obj ) {
    echo $id ' = ' $obj->descr ' and costs ' . $obj->price;
}

To change existing info

$_SESSION['cart'][$item]->qty += 1;

or

$_SESSION['cart'][$item]->qty = $newQty;

Upvotes: 2

user557846
user557846

Reputation:

i suggest this approach

$_SESSION['cart'] = array();

to add an item

$_SESSION['cart'][$item]= $qty;

then use the items id to manipulate:

delete:

unset($_SESSION['cart'][$item]);

change to known qty value:

$_SESSION['cart'][$item]= $qty;

add one:

$_SESSION['cart'][$item] += 1;

multiple variables for an item:

$_SESSION['cart'][$item]= array('qty'=>$qty,$descrip,$size,$colour);

Upvotes: 1

Related Questions