title: PHP and HTML remember checkbox value with same name after submit
body: <p>I have some some fields in a form that share the same name, they are automatically generated from a database table and I can't know how many would there be.</p>
  
  <pre><code>   &lt;div class="row w40 fl"&gt;
      &lt;label for="code" class="label"&gt;codice &lt;span class="form-notice"&gt;*&lt;/span&gt;&lt;/label&gt;
      &lt;input type="text" class="input" name="code" id="code" placeholder="Codice" value="&lt;?= Input::post('code') ?&gt;"&gt;
  &lt;/div&gt;
  
  &lt;div class="row w40 fr"&gt;
      &lt;label for="name" class="label"&gt;nome &lt;span class="form-notice"&gt;*&lt;/span&gt;&lt;/label&gt;
      &lt;input type="text" class="input" name="name" id="name" placeholder="Nome" value="&lt;?= Input::post('name') ?&gt;"&gt;
  &lt;/div&gt;
  
  &lt;?php foreach($categories as $cat): ?&gt;
      &lt;div class="w20 fl"&gt;
          &lt;label for=""&gt;&lt;?= ucwords($cat-&gt;name) ?&gt;&lt;/label&gt;
          &lt;input type="checkbox" name="cat[]" value="&lt;?= $cat-&gt;id ?&gt;" &lt;?= ($cat-&gt;id == Input::post('cat')) ? 'checked' : '' ?&gt;&gt;
      &lt;/div&gt;
  &lt;?php endforeach; ?&gt;
  </code></pre>
  
  <p>The problem is that if a error occurs after the submit, all the checked inputs will be lost. If they would have different names there wouldn't be any problem, but they always different.</p>
  
  <p>So after the submit, how can I remember the checked ones and check them ? Say the user check 5 of them, fills all the form inputs but leaves one blank. Obviously an error will pop out, but while all other inputs will have the data the user entered, the checkboxes won't, at least I don't know how to do it.</p>
  
  <p>Note that <code>Input::post('code')</code> means <code>(isset($_POST['code'])) ? $_POST['code'] : ''</code></p>
  
  <p>Thank you, hope you can suggest me a solution.</p>
  
  <p>Ok, so after more research here is the solution.</p>
  
  <pre><code>if ( isset($_POST['cat']) ) {
      foreach ($_POST['cat'] as $cbCat) {
          $selectedCat[$cbCat] = 'checked';
      }
  }
  
  &lt;?php foreach($categories as $cat): ?&gt;
      &lt;div class="w20 fl"&gt;
          &lt;label for="cat-&lt;?= $cat-&gt;id ?&gt;"&gt;&lt;?= ucwords($cat-&gt;name) ?&gt;&lt;/label&gt;
          &lt;input type="checkbox" id="cat-&lt;?= $cat-&gt;id ?&gt;" name="cat[]" value="&lt;?= $cat-&gt;id ?&gt;" &lt;?= (isset($selectedCat[$cat-&gt;id])) ? $selectedCat[$cat-&gt;id] : '' ?&gt; &gt;
      &lt;/div&gt;
  &lt;?php endforeach; ?&gt;
  </code></pre>