Skip to content
Advertisement

Show checkbox checked in the table

I have a problem showing the selected check value in the table. Now I cannot follow my selected value to show the check values in each row in the table.

For example below coding,I have the selected values following are true,false,true,false,true,false, I need to show these values in the checkbox, so I make these value to become checked or uncheck, if value is true then will checked, else will uncheck:

<?php 
$myString = "true,false,true,false,true,false";
$myArray = explode(',', $myString);

foreach ($myArray as $k => $va) { 
$check_val = $va;
}
if($check_val == "true"){
    $tick = "checked";
}else{
    $tick = " ";
}
?>

This is my working online editor: https://paiza.io/projects/D-J1uBPeHJuL8jCOhToRQQ

I want the expected result like below the picture, the selected values can follow by true,false,true,false,true,falsein each row in the table:

output1

Hope someone can guide me on how to solve this problem. Thanks.

Advertisement

Answer

In your code there is $tick value every time the same, for all checkboxes.

If you have tick values in array, than it’s quite easy. In each row check $myArray[X] value.

<td><input type="checkbox" id="checkbox_val" name="checkbox_val" value="0" <?php echo $myArray[0] === 'true' ? 'checked' : '';?>>&nbsp;</td>

You can do it in loop, than code would be st. like (expected you have contact&country in any array too)

<table>
    <tr><th>....</th></tr>
<?php
    foreach ($myArray as $k => $va) { 
?>
        <tr>
            <td>...</td>
            <td><input type="checkbox" id="checkbox_val" name="checkbox_val" value="0" <?php echo $va === 'true' ? 'checked' : '';?>>&nbsp;</td>
            <td><?php echo $contact[$k] ?></td>
            <td><?php echo $country[$k] ?></td>
        </tr>
<?php    
}
?>
</table>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement