title: Resolve Invalid argument for foreach() when adding sum of checkboxes
body: <p>Since I'm basically a designer and not a developer, I've bumped into a (probably pretty simple) problem that I can not seem to figure out.</p>
  
  <p><strong>My problem:</strong></p>
  
  <p>I want to add the value of the selected checkboxes together and display the sum of them as <code>$sum</code>. Pretty straightforward I thought, but I seem to <strong>(1)</strong> need some form of initial check if any checkboxes are posted to avoid <code>Warning: Invalid argument supplied for foreach()</code>, as well as <strong>(2)</strong> some kind of prevention from posting without selecting any checkbox at all.</p>
  
  <p>I've been trying to resolve my issue by looking at related threads such as <a href="https://stackoverflow.com/questions/2630013/invalid-argument-supplied-for-foreach">Invalid argument supplied for foreach()</a>, and I've tried to use the solutions mentioned there, but unfortunately without success – you can see the lines I've commented out, <code>if (is_array($product)) {</code>.</p>
  
  <p><strong>Goal</strong></p>
  
  <p>My end goal with this code is to create a form with let's say 3 segments/categories of checkboxes where the user <em>must</em> check at least one <code>in each segment</code> (they could check all if they'd like, in my sample code only the first segment/category is supplied). Each checked box will provide a value that goes towards adding them all in a sum.  </p>
  
  <p>I'm happy to see any alternative solutions and optimizations, as long as you can explain or point me to an example of your improvements, since I'm very much a beginner with PHP.</p>
  
  <p><strong>Index.php</strong>
      
  
  <pre><code>/* if (is_array($product)) { */
      foreach ($_POST['product'] as $name =&gt; $value) {
          $sum = array_sum(array_map('intval', $_POST['product']));
  
          echo('sum: '.$sum);
  
      }
  /* } */
  
  ?&gt;
  
  &lt;form action="index.php" method="post"&gt;
      &lt;label&gt;&lt;input type="checkbox" name="product[1]" value="100" /&gt;100&lt;br&gt;&lt;/label&gt;
      &lt;label&gt;&lt;input type="checkbox" name="product[2]" value="200" /&gt;200&lt;br&gt;&lt;/label&gt;
      &lt;label&gt;&lt;input type="checkbox" name="product[3]" value="300" /&gt;300&lt;br&gt;&lt;/label&gt;
  
      &lt;br&gt;
      &lt;input type="submit" name="submit"&gt;
  &lt;/form&gt;
  
  
  &lt;a href="index.php"&gt;reload&lt;/a&gt;
  </code></pre>