Page 1 of 1

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

Posted: Fri Sep 22, 2006 6:26 am
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);

Posted: Fri Sep 22, 2006 6:31 am
by n00b Saibot

Code: Select all

$_SESSION['products'] = array('id' => $id, 'quantity' => $quantity);

Posted: Fri Sep 22, 2006 7:29 am
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.

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

Posted: Fri Sep 22, 2006 8:15 am
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);
?>

Posted: Fri Sep 22, 2006 12:46 pm
by n00b Saibot
ah so you wanted to add elements into array... :roll:

Posted: Tue Sep 26, 2006 3:03 am
by flashharry82
Apologies for the slow reply.

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