Skip to content
Advertisement

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

HTML

<form action="submitchecklist.php" method="post">
  <table border="2">
  <thead>
      <th colspan="2">PLUMBING</th>  
  </thead>
<tbody>
    <tr>
        <td></td>
        <td>
            Leakage
        </td>
        <td>Heater</td>
    </tr>

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

</tbody>
</table>
</form>

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.

submitchecklist.php

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

Advertisement

Answer

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

leak[$i][yes].

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)
{
    if(isset($props['yes']))
       ....
    if(isset($props['no']))
       ....
}
8 People found this is helpful
Advertisement