如何阅读,如果一个复选框被选中在PHP?


当前回答

一个极简的布尔检查开关位置保留

<?php

$checked = ($_POST['foo'] == ' checked');

?>

<input type="checkbox" name="foo" value=" checked"<?=$_POST['foo']?>>

其他回答

在BS3中

  <?php
                  $checked="hola";
                  $exenta = $datosOrdenCompra[0]['exenta'];
                  var_dump($datosOrdenCompra[0]['exenta']);
                  if(isset($datosOrdenCompra[0]['exenta']) and $datosOrdenCompra[0]['exenta'] == 1){

                      $checked="on";

                  }else{
                    $checked="off";
                  }

              ?>
              <input type="checkbox" id="exenta" name="exenta" <?php echo $checked;?> > <span class="label-text"> Exenta</span>

请注意isset($datosOrdenCompra[0]['exenta'])的用法

当使用复选框作为数组时:

<input type="checkbox" name="food[]" value="Orange">
<input type="checkbox" name="food[]" value="Apple">

你应该使用in_array():

if(in_array('Orange', $_POST['food'])){
  echo 'Orange was checked!';
}

记得先检查数组是否被设置,例如:

if(isset($_POST['food']) && in_array(...
<form>
<input type="check" id=chk1 value="1">
<input type="check" id=chk2 value="1">
<input type="check" id=chk3 value="1">
</form>

当你检查chk2时,你可以看到如下值:

<?php
foreach($_POST as $key=>$value)
{
    if(isset($key))
        $$key=strip_tags($value);
}
insert into table (chk1,chk2,chk3) values ('','1','');
?>

Wordpress有checked()函数。 参考:https://developer.wordpress.org/reference/functions/checked/

checked( mixed $checked, mixed $current = true, bool $echo = true )

描述 比较前两个参数,如果相同则标记为选中

参数 美元的检查 (混合)(必选)要比较的值之一

当前美元 (混合)(可选)(true)如果不是true,要比较的另一个值 缺省值:true

美元的回声 (可选)是否返回或返回该字符串 缺省值:true

返回#返回 (string) HTML属性或空字符串

你可以用简短的if来表达:

$check_value = isset($_POST['my_checkbox_name']) ? 1 : 0;

或者使用新的PHP7空合并运算符

$check_value = $_POST['my_checkbox_name'] ?? 0;