Hi all,
I keep getting "Invalid argument supplied for foreach()" error message under certain circumstances.
I have two sets of arrays that I use to display a set of data. One of them is stored as a session variable, which chokes when being displayed.

display_cart($_SESSION['cart'], ...);

function display_cart($cart, ...)
{
  foreach ($cart as $optionid => $qty)
  {
    blah blah
  }

  if (isset($_SESSION['EOs']))
  {
    error_log("\nESSION['EOs'] is set, num items = ".count($_SESSION['EOs']),3,"debug.txt");
    error_log("\ndump_array(SESSION['EOs']) = ".dump_array($_SESSION['EOs']),3,"debug.txt");
    foreach ($_SESSION['EOs'] as $optionid=>$row)  // It chokes right here
    {
      blah blah
    }

I put the error_logs to see what values I get. I get "1" for the count, and "argument is not array" as the returned value of dump_array().

What I do prior to this situation is:
I add a new product through a php page that does not touch SESSION['EOs'] at all. This page (a form) collects user input and creates a new product and adds it to the database. Immidiately after this, if I go to the page, that up to this point was displaying everything properly, I get the "invalid argument supplied..." error message.
I don;t know how an array can become a non-array!

I appreciate your help.

function dump_array($array)
{
  if(is_array($array))
  {
    $size = count($array);
    $string = '';
    if($size)
    {
      $count = 0;
      $string .= '{ ';
      // add each element's key and value to the string
      foreach($array as $var => $value)
      {
        $string .= "$var = $value";
        if($count++ < ($size-1))
        {
          $string .= ', ';
        }
      }
      $string .= ' }';
    }
    return $string;
  }
  else
  {
    // if it is not an array, just return it
error_log("\nargument is not an array",3,"debug.txt");
    return $array;
  }
}

    You might also want to look at [man]var_dump[/man]. Without knowing anything about how $_SESSION['cart'] is being set, it's pretty much impossible to guess why it's not being set to an array value.

      Let me add a little bit of info...
      There is an admin page which allows the admin user to add/modify products, modify orders, ..., view cart.
      Once I go to this page and fill out the "Add a Product" form and submit and go to "View Cart" page I get the error message.
      Now, if I open a new window and go to admin page and do the add product thing, close the window and then go to view cart no errors appear. It seems it only happens if I go to "View Cart" page from within the Admin Page.
      In the code that processes the "Add a Product" request, there is not a line that touches the $_SESSION['EOs'] (i.e. the array that becomes a non-array)

        Is going through the Admin page effecting your session / classes try print_r $SESSION and the $SESSION['cart'] in the view cart page.

        This should let you see exactly whats going on - if is still an array both times then the logic is screwy somewhere else. ie in a function.

        If going via a link to the cart is the problem then you might not be saving back to the session correctly..

          I did some debugging and here is where the culprit is, although I am not sure what happens that screws things up:

          In my "Add a product" form, I have defined fields as:

          $conn = db_connect();
          $query = "SELECT BuilderID, BuilderName FROM Builders ORDER BY BuilderName";
          $res = mysql_query($query);
          while ($row = mysql_fetch_array($res))
          {
            echo "<tr>\n
              <td>Option Number</td>
              <td><input name=\"option_num".$row['BuilderID']."\" type=\"text\" size=\"20\"></td>\n
              <td>Option Price</td>\n
              <td><input name=\"option_price".$row['BuilderID']."\" type=\"text\" size=\"10\"></td>\n
              <td>Option Cost</td>\n
              <td><input name=\"option_cost".$row['BuilderID']."\" type=\"text\" size=\"10\"></td>\n
              <td>How many Electrical Outlets does it require (If any)</td>
              <td><input name=\"EO".$row['BuilderID']."\" type=\"text\" size=\"3\" maxlength=\"1\" value=\"0\"></td>\n
              <td>How Many Electrical Rough-In does it require (If any)</td>\n
              <td><input name=\"ER".$row['BuilderID']."\" type=\"text\" size=\"3\" maxlength=\"1\" value=\"0\"></td>\n
            </tr>\n
          }
          

          Then in the file that processes the form:

          $query = "SELECT BuilderID, BuilderName FROM Builders ORDER BY BuilderName";
          $res = mysql_query($query);
          while ($row = mysql_fetch_array($res))
          {
            $optionnum = $_POST['option_num'.$row['BuilderID']];
            $optionprice = $_POST['option_price'.$row['BuilderID']];
            $optioncost = $_POST['option_cost'.$row['BuilderID']];
            $EOs = $_POST['EO'.$row['BuilderID']];
            $ERs = $_POST['ER'.$row['BuilderID']];
          }
          

          Is the way I am accessing those form fields screwing things up?
          i.e. $_POST['ER'.$row['BuilderID']]

            Originally posted by NoBullMan
            Is the way I am accessing those form fields screwing things up?
            i.e. $_POST['ER'.$row['BuilderID']]

            Probably. Since it came from a form, it contains a string, not an array.
            You never actually do anything with those form fields. You assign the form values to variables, and then you assign the next bunch of form values to the same variables. Are $optionnum, $optionprice, $optioncost, $EO and $ER supposed to be arrays?

              Use the Explode feature to convert the string back into an array, if that is required.

              It may require more logic if you wish for set array keys etc..

                Hi guys, thanks for the replies.
                I actually do something with the variables but skipped adding the code. Right after the assignments of the POSTed info to variables, I do:

                $query = "INSERT INTO PriceOptions VALUES 
                     ('','".$row['BuilderID']."', '$itemid', '$optionnum', '$optionprice', '$optioncost', '$EOs', '$ERs')";
                      $presult = mysql_query($query);
                

                The variables $optionnum, $optionprice,...$EO, $ER are NOT arrays.
                I have a session variable called $SESSION['EOs'] that has this form:
                $SESSION['EOs'][<some option number>]['qty']
                $
                SESSION['EOs'][<same option number>]['location']
                etc.
                It is this array that becomes non-array right after the code I had included in my previous post (right after assignment of form fields to variables and before insertion into D😎.
                Just before the code it is still an array (I used error_log() to check this), right after the code it becomes non-array. That's whay I thought that something in the code is destroying that session var.
                After the code the session varaible is still set (if isset() returns TRUE) but "if is_array()" returns FALSE.

                  The variables $optionnum, $optionprice,...$EO, $ER are NOT arrays.
                  I have a session variable called $SESSION['EOs'] that has this form:
                  $SESSION['EOs'][<some option number>]['qty']
                  $
                  SESSION['EOs'][<same option number>]['location']
                  etc.

                  OK - so after running the query it becomes a string ?

                  You're not saving $EOs into the session after the query ? Thus destroying the session array?

                  Also you're not setting the $SESSION['EOs'] = dump_array($SESSION['EOs']) are you as this would convert your array into string and put it back into the session ?

                  If you can still access the session then your session hasn't been destroyed / corrupted - so something must be setting the EOs variable 😕

                    Thanks RossCo. The session variables becomes a string before the query is run (that's why I did not include it in the previous posting). It becomes a string right after the assignment of form fields to variables!!
                    I am not touching SESSION['EOs'] at all in the file that processes the form submission!
                    I use dump_array within the error_log() function to see if I get an array listing or an error message that the argument is not an array. So, prior to the form field assignments, dump_array($SESSION['EOs']) list the array elements, right after it says "argument is not an array"!!
                    All I am doing is creating a new option (a new product) by extracting the information from the form fields that user submitted and inserting them into the DB. Some options/products have ELectrical Outlets associated with them ($EOs). The $
                    SESSION['EOs'], on the other hand, keeps track of options/products added to the cart that have electrical outlets associted with them. Because the session var becomes a string, the shopping cart shows no electrical outlets, even though some products do need them, whereas prior to this situation it was showing the outlets.

                    error_log("\nprior to getting values from form (POST)...",3,"debug.txt");
                    error_log("\nnumber of items in EOs = ".array_count_values($_SESSION['EOs']),3,"debug.txt");
                    error_log("\nitems in EOs = ".dump_array($_SESSION['EOs']),3,"debug.txt");
                    
                    // The above error_log() gives the correct values
                    
                      $optionnum = $_POST['option_num'.$row['BuilderID']];
                      $optionprice = $_POST['option_price'.$row['BuilderID']];
                      $optioncost = $_POST['option_cost'.$row['BuilderID']];
                      $EOs = $_POST['EO'.$row['BuilderID']];
                      $ERs = $_POST['ER'.$row['BuilderID']];
                    
                    error_log("\nafter getting values from form (POST)...",3,"debug.txt");
                    error_log("\nnumber of items in EOs = ".array_count_values($_SESSION['EOs']),3,"debug.txt");
                    error_log("\nitems in EOs = ".dump_array($_SESSION['EOs']),3,"debug.txt");
                    
                    // This error_log() tells me argument is not an array
                    

                      hmm... Puzzling!

                      Ok Put some debugging into your code to root out where its amending the session variable.

                      From the code I can't see any obvious problems, you don't have registered global variables on ?

                      Try:

                      print_r($_SESSION['EOs']);
                        $EOs = $_POST['EO'.$row['BuilderID']];
                      print_r($_SESSION['EOs']);
                      die();
                        $ERs = $_POST['ER'.$row['BuilderID']]; 
                      

                      If it is setting the $EOs and replacing the session variable you should see it there from the printed outputs.

                      Otherwise I haven't used error_log - but if the first option fails check that isn't effecting the session variable before the $EOs is set:

                        print_r($_SESSION['EOs']);
                      error_log("\nprior to getting values from form (POST)...",3,"debug.txt");
                      error_log("\nnumber of items in EOs = ".array_count_values($_SESSION['EOs']),3,"debug.txt");
                      error_log("\nitems in EOs = ".dump_array($_SESSION['EOs']),3,"debug.txt"); 
                        print_r($_SESSION['EOs']);
                      die(); 
                      

                      This way you should pinpoint exactly whats happening to your session variable!

                      RossC0

                        OK, so I put the print_r before and after some statements and I narrowed it to one statement:

                        error_log("\nprint_r(SESSION['EOs']) = ".print_r($_SESSION['EOs'], true),3,"debug.txt");
                        	  $EOs = $_POST['EO'.$row['BuilderID']];
                        error_log("\nprint_r(SESSION['EOs']) = ".print_r($_SESSION['EOs'], true),3,"debug.txt");
                        

                        What I got was:

                        print_r(SESSION['EOs']) = Array
                        (
                            [1100] => Array
                                (
                                    [qty] => 1
                                    [optionname] => 4-Zone Speaker with Volume Control
                                    [outletid] => EL17005
                                    [outletname] => 20-amp Dedicated Outlet
                                    [price] => 100
                                )
                        
                        )
                        
                        print_r(SESSION['EOs']) = 0
                        

                        The only thing suspicious-looking was the variable name ($EOs) that looked similar to the session varaible ($_SESSION['EOs']). So, I changed the variable name from $EOs to $elec_outlets and the problem went away 😕
                        Morale: Don't name a variable same as your session variable!

                          Well thats solves it! You must have register_globals set as on.

                          This can have serious security implications, which if you're building a sales cart / application you should be aware of.

                          Check out: www.php.net/register_globals

                          RossC0

                            Write a Reply...