Why does this $_SESSION code not work as intended?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Yko
Forum Newbie
Posts: 3
Joined: Wed Feb 09, 2011 12:03 pm

Why does this $_SESSION code not work as intended?

Post 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!!!!
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

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

Post 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);
Starkid225
Forum Newbie
Posts: 9
Joined: Mon Feb 07, 2011 10:28 pm

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

Post by Starkid225 »

Try adding a session start before the variable.

Code: Select all

session_start();

$_SESSION['cart'] = array();
Last edited by Starkid225 on Tue Feb 15, 2011 7:08 pm, edited 1 time in total.
Yko
Forum Newbie
Posts: 3
Joined: Wed Feb 09, 2011 12:03 pm

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

Post by Yko »

Ok. Thanks for the reply! I think I'll figure it out!
Domsore
Forum Commoner
Posts: 46
Joined: Wed Jan 26, 2011 7:07 pm

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

Post by Domsore »

@starkid -- session_start();
Starkid225
Forum Newbie
Posts: 9
Joined: Mon Feb 07, 2011 10:28 pm

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

Post by Starkid225 »

Yes thats what a meant. Sorry... :cry:
Post Reply