Home  >  Article  >  Backend Development  >  How to get the values ​​of radio buttons and check buttons in php form (example)

How to get the values ​​of radio buttons and check buttons in php form (example)

PHPz
PHPzOriginal
2017-04-04 14:30:012064browse

Get the value of the radio button in the form in the php code: (The radio button can only allow us to select one. There is a "checked" attribute here, which is used to select it by default. Every time we refresh our page It defaults to this value.)

Example:

<form name="myform" action="" method="post">

Gender:

<input type="radio" name="sex" value="男" checked />男<input name="sex" type="radio" value="女" />女
<input type="submit" name="submit" value="提交" />
</form>
<?php
echo "您的选择是:";
echo $_POST["sex"];
?>

If you select male, the value that comes out will be "male". is female, the value that comes out is "female".

Get the value of the check box in the php code: (The check box allows us to select multiple times. They exist at the same time. In order to facilitate the transfer of values, we set the name to an array.)

The format is:

<input type="checkbox" name="chkbox[]" value="chkbox1" />

Method: Use the count() function to calculate the size of the array in the return page, and combine it with a for loop statement to output the value of the selected check box.

Example:

<form action="" name="form1" method="post">

Your favorite number:

<input type="checkbox" name="mrbook[]" value="1" />1
<input type="checkbox" name="mrbook[]" value="2" />2
<input type="checkbox" name="mrbook[]" value="3" />3
<input type="checkbox" name="mrbook[]" value="4" />4
<input type="submit" name="submit" value="提交" />
</form>
<?php
if($_POST[&#39;mrbook&#39;]!=null)
{
       echo "您选择的数字是:";
       for($i=0;$i<count($_POST[&#39;mrbook&#39;]);$i++)
       {
              echo $_POST[&#39;mrbook&#39;][$i]."  ";
       }
}
?>

We have to learn to use arrays to solve our problems! ! ! !

The above is the detailed content of How to get the values ​​of radio buttons and check buttons in php form (example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn