François Mari
François Mari

Reputation: 61

Multiple checkbox selected in a loop PHP

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.

Upvotes: 0

Views: 959

Answers (1)

Axel Coudair
Axel Coudair

Reputation: 41

<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">

Upvotes: 1

Related Questions