Page 1 of 1

Why does this $_SESSION code not work as intended?

Posted: Wed Feb 09, 2011 12:11 pm
by Yko
Hey,

I am new to PHP and new to DevNetwork. I am learning PHP and cannot figure out why this is the case.

Suppose you have a session:

Code: Select all

$_SESSION['cart'] = array();
I am looking at an ecommerce example from Munach book and it is coded:

Code: Select all

$_SESSION['cart'][$product_id] = round($quantity, 0);
which is translated to be session_as_array[key] = someNumber

but then I start playing around and change it to this:

Code: Select all

$temp_session = $_SESSION['cart'];
$temp_session[$product_id] = round($quantity,0);
To me, as a beginner this code is easier to understand. After I made the change, I believe it still adds the item to the cart but other parts of the code does not work which leads me to believe that the two are not completely equal. Can someone explain to me why?

Thanks!!!!

Re: Why does this $_SESSION code not work as intended?

Posted: Wed Feb 09, 2011 12:32 pm
by John Cartwright

Code: Select all

$temp_session = $_SESSION['cart'];
$temp_session[$product_id] = round($quantity,0);
You either need to set a reference to $_SESSION['cart'] or write directly to $_SESSION. I.e.,

Code: Select all

$temp_session = &$_SESSION['cart'];
$temp_session[$product_id] = round($quantity,0);

//or 

$_SESSION['cart'][$product_id] = round($quantity,0);

Re: Why does this $_SESSION code not work as intended?

Posted: Wed Feb 09, 2011 4:04 pm
by Starkid225
Try adding a session start before the variable.

Code: Select all

session_start();

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

Re: Why does this $_SESSION code not work as intended?

Posted: Wed Feb 09, 2011 4:51 pm
by Yko
Ok. Thanks for the reply! I think I'll figure it out!

Re: Why does this $_SESSION code not work as intended?

Posted: Wed Feb 09, 2011 7:06 pm
by Domsore
@starkid -- session_start();

Re: Why does this $_SESSION code not work as intended?

Posted: Tue Feb 15, 2011 7:06 pm
by Starkid225
Yes thats what a meant. Sorry... :cry: