I have user titles, which are stored in database in this way. 1,2,6,10 and etc. I want to check if the user already has this titles and if he does, to check the check box.
<?php
$user_titles = explode(',', $user['titles']);
//foreach($user_titles as $uTitles){
//echo $uTitles;
//}
?>
<input type="checkbox" name="title[]" value="1">Test1<br/>
<input type="checkbox" name="title[]" value="2">Test2<br/>
<input type="checkbox" name="title[]" value="3">Test3<br/>
您需要将checked
属性添加到checked
属性。
<input type="checkbox" name="title[]" value="1" <?php if(in_array(1, $user_titles) echo 'checked="checked"'; ?>>Test1<br/>
If i understand correctly you have the values stored as a string delimited by a comma.
Use an iteration method, for example:
<?php $checked = ''; ?>
<?php for($i = 1; $i <= count($possible_checkbox); $i++ ) {
if(in_array($i, $user_titles ) ) { $checked = 'checked'; } else {$checked = '' }
?>
<input type="checkbox" value="<?php echo $i; ?>" name="title[]" <?php echo $checked; ?> />
<?php } ?>
Hope it helps.
Move the titles to new array and iterate trough them. Inside the loop, check if the value is in the $user_titles array and add 'checked' to the input tag.
<?php
$titles = [
1 => "Test1",
2 => "Test2",
3 => "Test3",
];
foreach ($titles as $value => $title) {
$checked = in_array($value, $user_titles) ? 'checked' : '';
echo '<input type="checkbox" name="title[]" value="' . $value . '" ' . $checked . '>' . $title . '<br/>';
}
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.