Skip to content

Trying to get array from form post but not working correcty

I am building an application with php

I have a form which contains an array of checkboxes as shown in the picture below

I want to the values accordingly but it is not working as expected

The form was generated with php for loop


<form action="submitchecklist.php" method="post">
  <table border="2">
      <th colspan="2">PLUMBING</th>  

    for ($i = 201; $i <= 215; $i++) {
        echo '
            <td>' . $i . '</td>
                <input type="checkbox" value="yes" name="leak_yes[]" id="">Yes
                <input type="checkbox" value="no" name="leak_no[]" id="">No
                <input type="checkbox" name="heat_yes[]" id="">Yes
                <input type="checkbox" name="heat_no[]" id="">No
    } ?>


I am trying to get the selected values but not working as expected.

leaked_no shows only when leaked yes is selected otherwise it will ignored

If I select 6 leaked_yes and 8 leaked_no it shows 7 leaked_yes and 7 leaked_no.


if (isset($_POST['leak_yes'])) {
    $leak_no = $_POST['leak_no'];
    $leak_yes = $_POST['leak_yes'];
    if (is_array($_POST['leak_yes'])) {
        $initalValue = 201;
        foreach ($_POST['leak_yes'] as $key => $value) {
            echo ($initalValue + $key);
            echo (isset($leak_yes[$key])) ? $leak_yes[$key] : "";
            echo "<br />";
            echo (isset($leak_no[$key])) ? $leak_no[$key] : "";
            echo "<br />";

enter image description here

enter image description here



Don’t use the name like leak_yes[], instead define the name as the following form:


The corresponding array element will be missing when the Yes or No checkbox is unchecked, but you are able to use foreach and isset to skip them.

HTML example:

<input type="checkbox" value="yes" name="leak['.$i.'][yes]" id="">Yes
<input type="checkbox" value="no" name="leak['.$i.'][no]" id="">No

PHP example:

foreach($_POST['leak'] as $i => $props)
User contributions licensed under: CC BY-SA
8 People found this is helpful