Home » Php » html – How to pair the values of these two arrays in PHP?

html – How to pair the values of these two arrays in PHP?

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a table with some items on it and each row has a checkbox and a textarea. When I pres submit I want to take the values of the textareas ONLY for the respective checked checkbox and NOT for the ones that aren’t checked even if they have textareas with some content.

                <form method="post">
                <?php if (!empty($arr_devices)) { ?>
                    <?php foreach ($arr_devices as $device) : ?>
                        <tr>
                            <td>
                                <input type="checkbox" name="devices[]" value="<?php echo $device["id"].$dev_comment ?>">
                            <td>
                           <td>  
<div class="input-group">
                                    <textarea name="dev_comment[]" placeholder="comment" rows="1" cols="50"><?php echo $dev_comment; ?></textarea>
                                </div>
                            </td>

                        </tr>
                    <?php endforeach; ?>
                <?php } ?>
                <input class="btn" type="submit" name="submit" value="Report">
                <form>

Printed arrays after summitted:

  Device_id([0] => 790 [1] => 1140 [2] => 1142 ) 
  Comments( [0] => sdf [1] => sdfsdfs [2] => [3] => fsdfsd [4] => )

as it is now, I am able to receive ONLY the device_id for the checked ones but ALL the values(even empty ones) for the comments when I am submitting. Why is that happening and how to fix it?

How to&Answers:

Only checked checkboxes will be submitted. You can keep the checkbox and textarea values paired by adding the same key to their name arrays. The device ID would probably work well for that.

<td>
    <input type="checkbox" name="devices[<?php echo $device["id"] ?>]" value="<?php echo $device["id"].$dev_comment ?>">
<td>
    <div class="input-group">
        <textarea name="dev_comment[<?php echo $device["id"] ?>]" placeholder="comment" rows="1" cols="50"><?php echo $dev_comment; ?></textarea>
    </div>
</td>

If the device id is not unique, you can just use the index from the foreach loop.

Then in the form handler code you can use that shared id from the checkboxes to access the comments:

foreach ($_POST['devices'] as $id => $value) {
    // do something with $_POST['dev_comment'][$id]
}