Keep checkbox check after submit (if checkbox is in an array) using Pho

I inherited code from an old server. This is the code:

<ul>
                        <?php
                            $field = get_field_object('field_591de98804dfb');
                            $choices = $field['choices'];
                        ?>
                        <?php foreach ($choices as $sector) : ?>
                            <li>
                                <label>
                                    <input type="checkbox" name="sector[]" value="<?php print $sector; ?>" <?php /* if ( $sector, array($_GET['sector']) ) : ?> checked <?php endif; */ ?> <?php if (in_array($sector, $_POST['sector'])) echo "checked='checked'"; ?> >
                                    <span class="checkbox"></span> <span class="label"><?php print $sector; ?></span>
                                </label>
                            </li>
                        <?php endforeach; ?>
                   </ul>

The code works on the old server to filter and the checkboxes remain checked even after the form is submitted. I am on Php 5.6 and I get the following error/s: Warning : in_array() expects parameter 2 to be array, null given in…

I tried changing the filter to: <?php if (in_array($sector, $_POST['sector'])) echo "checked='checked'"; ?> and it’s not woking, idea pointers or ides?

If no checkboxes are checked, neither $_POST['sector'] nor $_GET['sector'] will exist, hence you need a default value. I would recommend to use filter functions (http://php.net/filter-input) to cover that case.

As @Dormilich has noted, you need to have a default value in case no sectors are selected. This code is untested but should do the trick.

<ul>
  <?php
    $field = get_field_object('field_591de98804dfb');
    $choices = $field['choices'];

    // Grab posted sectors defaulting to empty array
    $sectors = [];
    if (isset($_GET ['sector'])) $sectors = $_GET ['sector'];
    if (isset($_POST['sector'])) $sectors = $_POST['sector'];
    ?>
  <?php foreach ($choices as $sector) : ?>
    <li>
      <label>
        <input type="checkbox" name="sector[]" value="<?php print $sector; ?>"
          <?php if (in_array($sector, $sectors)) echo "checked='checked'"; ?> >
        <span class="checkbox"></span> <span class="label"><?php print $sector; ?></span>
      </label>
    </li>
  <?php endforeach; ?>
</ul>
1 Like

Thank you, @ahundiak

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.