Each call to itemsincart() will change when you've modified the data within the session:
PHP Code:
$_SESSION['cart'][itemsincart()][0] = $_POST['addproductid']; // add a new product onto the end of the array
$_SESSION['cart'][itemsincart()][1] = $_POST['productquantity']; // quantity of new product
So, assuming cart is completely empty, the first one returns a result of 0. The second one returns a result of 1. So you have effectively written:
PHP Code:
$_SESSION['cart'][0][0] = $_POST['addproductid'];
$_SESSION['cart'][1][1] = $_POST['productquantity'];
where each additional item will work the same fashion. So adding another one writes to [1][0] and [2][1], and so forth.
You need to capture the results of count, but I'd question its overall use. PHP doesn't require you to specify the incremental counter of an item placed within an array. Simply using $aValues[] will append to the existing map.
You should instead check if an item exists, and if so increment it. That's up to you if you want to do that, but to me that makes more sense. I'd also suggest limiting the number of superglobal calls as much as you can, as it helps keep your code more portable.
PHP Code:
function addToCart(array &$aCart, $itm, $qty) // assuming $itm and $qty are both ints.
{
if (is_int($itm) && is_int($qty) && $qty > 0)
{
// Here you have to decide on the absolute structure. I'll continue with what you have.
$bModified = false;
$iItemsInCart = count($aCart);
for ($i = 0; $i < $iItemsInCart && !$bModified; ++$i)
{
if ($aCart[$i][0] == $itm)
{
$aCart[$i][1] += $qty;
$bModified = true;
}
}
if (!$bModified)
{
// Not yet in cart.
$aCart[] = array($itm, $qty);
}
}
}
addToCart($_SESSION['cart'], 1, 8);
addToCart($_SESSION['cart'], 3, 2);
addToCart($_SESSION['cart'], 1, 1);
For example.
If you key them instead, its actually easier since you don't need to loop at all:
PHP Code:
function addToCartKey(array &$aCart, $itm, $qty)
{
if (is_int($itm) && is_int($qty) && $qty > 0)
{
if (!isset($aCart[$itm]))
{
$aCart[$itm] = 0;
}
$aCart[$itm] += $qty;
}
}
addToCart($_SESSION['cart'], 1, 8);
addToCart($_SESSION['cart'], 3, 2);
addToCart($_SESSION['cart'], 1, 1);
The difference is the results, the first one would end up like so for $_SESSION['cart']:
Code:
Array
(
[0] => Array
(
[0] => 1
[1] => 9
)
[1] => Array
(
[0] => 3
[1] => 2
)
)
While the key level would end up like so:
Code:
Array
(
[1] => 9
[3] => 2
)
Both are valid options, but depend completely on what the rest of your code does.