0

I have a loop that offers several checkboxes to the user:

<?php
while($personInfo = $selectPerson->fetch())
{
?>

    <label>
    <input type="checkbox" name="checkBoxValue[]" id="checkBoxValue" value="<?= $personInfo['title'] ?>"> <?= $personInfo['title'] ?>&nbsp&nbsp&nbsp
    </label> | 
    <label>
    <input type="checkbox" name="improper" id="improper" value="0"> Improper
    </label>
    <hr>

<?php
}
?>

The thing is that I manage to recover each checkbox selected by the user with:

foreach($_POST['checkBoxValue'] as $selected)
{
    echo $selected;
    echo "<hr>";
}

But I do not see how I can know if for each checkbox selected, the checkbox "Improper" is also selected.

7
  • Same way as you did the checkBoxValue one name="improper[]" Commented Jun 19, 2018 at 12:58
  • along with @DarkBee ans.make sure your id is unique. this is not in your case. Commented Jun 19, 2018 at 13:00
  • @DarkBee Hmmm except if checkboxes are not checked they are not returned to the PHP. So if the first checkbox checkboxValue is checked and second improper is checked they will both be returned in the [0]'th occurance leading to MAJOR confusion and errors Commented Jun 19, 2018 at 13:01
  • Well it's actual better to indicate which checkbox belongs with which person by changing it up <input type="checkbox" name="checkBoxValue[<?= $personInfo['id'] ?>]" id="checkBoxValue_<?= $personInfo['id'] ?>"> - Then you just can use an isset check combined with the id of the person Commented Jun 19, 2018 at 13:08
  • Thanks, but I don't know the ID of the person.. Commented Jun 19, 2018 at 13:35

1 Answer 1

1
<form method="post" action="#" name="stackOverflow">
<?php
$personInfo = [['id' => 2,  'title' => "Bernard"], [ 'id' => 3, 'title' => "Marc"]];
foreach ($personInfo as $info) {
    ?>
    <label>
        <input type="checkbox" name="checkBoxValue[<?php echo $info["id"] ?>]" id="checkBoxValue<?php echo $info["id"]; ?>" value="<?= $info['title'] ?>"
            <?php if (isset($_POST['checkBoxValue'][$info["id"]])) { ?>
                checked
            <?php } ?>
        >
        <?= $info['title'] ?>&nbsp&nbsp&nbsp</label> | <label>
        <input type="checkbox" name="improper[<?php echo $info["id"] ?>]" id="improper_<?php echo $info["id"]; ?> "
            <?php if (isset($_POST['improper'][$info["id"]]) && "on" === $_POST['improper'][$info["id"]]) { ?>
                checked
            <?php } ?>
        >
        Improper
    </label>
    <hr>
    <?php
}
?>
<input id="submit" type="submit" name="btn_validation" value="submit">

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.