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


当前回答

<?php

  if (isset($_POST['add'])) {

    $nama      = $_POST['name'];
    $subscribe = isset($_POST['subscribe']) ? $_POST['subscribe'] : "Not Checked";

    echo "Name: {$nama} <br />";
    echo "Subscribe: {$subscribe}";

    echo "<hr />";   

  }

?>

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST" >

  <input type="text" name="name" /> <br />
  <input type="checkbox" name="subscribe" value="news" /> News <br />

  <input type="submit" name="add" value="Save" />

</form>

其他回答

如果你的HTML页面是这样的:

<input type="checkbox" name="test" value="value1">

提交表单后,您可以检查它:

isset($_POST['test'])

or

if ($_POST['test'] == 'value1') ...
<?php

  if (isset($_POST['add'])) {

    $nama      = $_POST['name'];
    $subscribe = isset($_POST['subscribe']) ? $_POST['subscribe'] : "Not Checked";

    echo "Name: {$nama} <br />";
    echo "Subscribe: {$subscribe}";

    echo "<hr />";   

  }

?>

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST" >

  <input type="text" name="name" /> <br />
  <input type="checkbox" name="subscribe" value="news" /> News <br />

  <input type="submit" name="add" value="Save" />

</form>

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

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

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

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

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

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

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

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

<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(...

根据表单的操作,您可以在$_POST或$_GET数组中检查相应的值是否已设置且非空。

例如:使用一个名为"test"的POST表单(即:<input type="checkbox" name="test">,你会使用:

if(isset($_POST['test']) {
   // The checkbox was enabled...

}