Is there a more efficient way of doing this? (Newbie)

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
flashharry82
Forum Newbie
Posts: 3
Joined: Fri Sep 22, 2006 6:11 am

Is there a more efficient way of doing this? (Newbie)

Post by flashharry82 »

Was putting a 2D array into a session variable but found that it needed to be updated in an ordinary array before being assigned to the session.

Code: Select all

if(isset($_SESSION['products'])) {
	$products = $_SESSION['products'];
	$products[] = array('id' => $id, 'quantity' => $quantity);
	$_SESSION['products'] = $products;
}

else {
	$products[] = array('id' => $id, 'quantity' => $quantity);
	$_SESSION['products'] = $products;
}
The above code works fine.

Tried the following code but it doesn't work.

Code: Select all

$_SESSION['products[]'] = array('id' => $id, 'quantity' => $quantity);
User avatar
n00b Saibot
DevNet Resident
Posts: 1452
Joined: Fri Dec 24, 2004 2:59 am
Location: Lucknow, UP, India
Contact:

Post by n00b Saibot »

Code: Select all

$_SESSION['products'] = array('id' => $id, 'quantity' => $quantity);
flashharry82
Forum Newbie
Posts: 3
Joined: Fri Sep 22, 2006 6:11 am

Post by flashharry82 »

Thanks, but that just resets the array on every new assignment i.e. It just changes index 0 every time instead of adding to a new index.
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Re: Is there a more efficient way of doing this? (Newbie)

Post by RobertGonzalez »

Try this...

Code: Select all

<?php
// Start out session
session_start();

// Add to/Set the products Session array
$_SESSION['products'][] = array('id' => $id, 'quantity' => $quantity);
?>
User avatar
n00b Saibot
DevNet Resident
Posts: 1452
Joined: Fri Dec 24, 2004 2:59 am
Location: Lucknow, UP, India
Contact:

Post by n00b Saibot »

ah so you wanted to add elements into array... :roll:
flashharry82
Forum Newbie
Posts: 3
Joined: Fri Sep 22, 2006 6:11 am

Post by flashharry82 »

Apologies for the slow reply.

Perfect, should really have thought of tryin that though. :oops:
Post Reply