Hi,
I'm trying to build a lightbox for a photographer's website. It's basically like a shopping cart but without the prices and checkout part. I just need to create an array stored in a session and be able to add to it.

So first, how do I store an array in a session?
Second, how do I add to the array everytime a new image is added to the lightbox?

    You can write an array to the $SESSION in the same way you write any variable. And to add items you can either add them to the array itself and then update the array in $SESSION, or treat $_SESSION as a 2d array:

    session_start();
    
    // Storing arrays in $_SESSION
    $array = array(1, 2, 3, 4);
    $_SESSION['array'] = $array;
    
    // Add then update method
    $array[] = 5;
    $_SESSION['array'] = $array;
    
    // 2D array method
    $_SESSION['array'][] = 6;
    
    session_destroy();
    

    Hope this helps.

      Thanks,
      I tried this but now my problem is that I can't seem to get it to display the contents of the session array. Since I can't display it I can't tell if this is working. When I try to use a foreach statement it doesn't like it. I used the following code:

      foreach ($_SESSION['array'][] as $value)
      {
      echo $value;
      }

      and it gives me an error message about the foreach line. How do I go about calling and displaying all of the items in the array? I need some kind of loop but I just don't seem to be able to walk through the array. Also, is there a function to tell me how many values are in the array?

      thanks

        You have it almost right - you dont need the extra []s in the foreach line. Foreach takes an array, and a variable to insert the value from the array into.

        foreach($_SESSION['array'] as $value)
        {
        echo $value;
        }
        
        // OR if you need the keys
        
        foreach($_SESSION['array'] as $key=>$value)
        {
        echo $key .'-'. $value; 
        }
        
          Write a Reply...