Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Jul 2012
    Posts
    11
    Thanks
    1
    Thanked 1 Time in 1 Post

    problem with a single mutidimiensional array element

    Hi guys,

    I've got a problem with a simple shopping cart I am trying to make. I am new to php so sorry if the code seems lame...

    here are the two functions isolated around my problem...

    PHP Code:
    function itemsincart() //returns total items in cart
          
    {
             
    $i=0;
             while(isset(
    $_SESSION['cart'][$i][0])) { $i++; }
             return (
    $i);
          }
          
    //----------------------------------------------------------------------------------------------------------------------------------------------------


    function addtocart() // add the product to the cart using the product id.
       
    {
          if(isset(
    $_POST['addproductid'])) // new products waiting to be added to cart from addtocart form
                
    {
                   
                   
    $_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
                   
    unset($_POST['addproductid']);
                   unset(
    $_POST['productquantity']);
                   echo 
    $_SESSION['cart'][itemsincart()][1]." * Product ".$_SESSION['cart'][itemsincart()][0]." added to cart";
                }
          } 
    The cart items are stored in the array $_SESSION['cart'] [][]

    $_SESSION['cart'] [x] is where I keep my cart item number
    $_SESSION['cart'] [x][0] - the product ID for the cart item number
    $_SESSION['cart'] [x][1] - the quantity

    the problem is, every time I add 1 item to a cart, for the first time the quantitiy isn't stored, but it is for every single other item after that.

    In other words
    PHP Code:
    $_SESSION['cart'] [0][1
    for some reason refuses to hold a value.

    Even if I hard set
    PHP Code:
    $_SESSION['cart'] [0][1] = 
    then
    PHP Code:
    echo $_SESSION['cart'] [0][1]; 
    I get a blank value back. It's only for that one single element, everything else works fine :/

    What is going on, can anybody shed some light here, I am pulling my hair out. Worst when you're trying to learn this stuff.

    Much appreciated!

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,979
    Thanks
    4
    Thanked 2,659 Times in 2,628 Posts
    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'], 18);
    addToCart($_SESSION['cart'], 32);
    addToCart($_SESSION['cart'], 11); 
    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'], 18);
    addToCart($_SESSION['cart'], 32);
    addToCart($_SESSION['cart'], 11); 
    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.

  • #3
    New Coder
    Join Date
    Jul 2012
    Posts
    11
    Thanks
    1
    Thanked 1 Time in 1 Post
    Ahh yes I seen the error in my ways,

    I shouldn't continue to call my itemsincart() function ..

    so what I did was $_itemsincart = itemsincart();

    and just used the variable instead of the function each time so the results were consistent.

    PHP Code:

    function addtocart() // add the product to the cart using the product id.
        
    {
            if(isset(
    $_POST['addproductid'])) // new products waiting to be added to cart from addtocart form
                    
    {
                        
                        
    $_itemsinarray itemsincart();
                        
    $_SESSION['cart'][$_itemsinarray][0] = $_POST['addproductid']; // add a new product onto the end of the array
                         
    $_SESSION['cart'][$_itemsinarray][1] = $_POST['productquantity']; // quantity of new product
                        
    unset($_POST['addproductid']);
                        unset(
    $_POST['productquantity']);
                        
                        echo 
    $_SESSION['cart'][$_itemsinarray][1]." * Product ".$_SESSION['cart'][$_itemsinarray][0]." added to cart";
                    }
            } 

    Now it works properly!, I looked at your code examples for alternative methods. But I am too much of a newb and I am just going to continue with the way I have done it so I don't confuse myself any further.

    Thanks for your suggestions and help, I can see I am going to learn a lot in these forums ..

    As for you...



  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •