How to deal with unchecked checkbox array value without javascripts?

admin

Administrator
Staff member
Suppose I have a form like this, where checkboxes are repeating fields:

Code:
<form action="" method="post">
    <?php for($i=0; $i<3; $i++) { ?>
       <input type="checkbox" name="ch[]" value="1">
    <?php } ?>
    <button type="submit" name="submit">submit</button>
</form>

I'm on WordPress and using custom meta boxes for dealing with it. So I declared the form within the callback function of the metabox, and receiving the values in another save function that's hooked with
Code:
save_post
and
Code:
new_to_publish
action hooks.

So what's happening: when I click on the button, the metabox callback submitted the form, and the hooked function receives it. (Can be visible at <a href="https://codex.wordpress.org/Function_Reference/add_meta_box" rel="nofollow noreferrer">
Code:
add_meta_box()
</a> WordPress Codex) Suppose my save function contains:

Code:
&lt;?php
if( isset($_POST['submit']) ) {
    $chb = $_POST['ch'];
    $result = array();
    foreach ($chb as $cb) {
        $result[] = array( 'isactive' =&gt; $cb );
    }
    var_dump($result);
}
?&gt;

It's showing that, checkboxes are not returning any value when unchecked. I considered all the server-side solutions mentioned here: <a href="https://stackoverflow.com/q/1809494/1743124">Post the checkboxes that are unchecked</a>

PROBLEM is, whenever the form is submitted, it's taking the checkboxes' values to an array(), so I can't check the array values like:

Code:
if( !isset( $_POST['ch'] ) || empty( $_POST['ch'] ) ) {
    $chb = 0;
} else {
    $chb = 1;
}

I also tried hidden field with
Code:
0
value, accompanied with
Code:
array_unique()
, but nothing seems work for me.

How can I deal with unchecked checkboxes in an array so that they can't be null, and my foreach can loop through all of 'em and store data accordingly, and correct?

I want to avoid JavaScripts solutions.