Problem
I use select as below:
<select name="taskOption">
<option>First</option>
<option>Second</option>
<option>Third</option>
</select>
In PHP, how can I grab the value of the pick option and save it in a variable for later use?
Asked by Felicia Tan
Solution #1
Use this way:
$selectOption = $_POST['taskOption'];
However, it is always preferable to include values for your option> tags.
<select name="taskOption">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
Answered by Praveen Kumar Purushothaman
Solution #2
The $_POST array’s values can be accessed by their key. Because $_POST is an associative array, you’d need $_POST[‘taskOption’]; to get to taskOption.
Before proceeding, double-check that it is there in the $_POST array.
<form method="post" action="process.php">
<select name="taskOption">
<option value="first">First</option>
<option value="second">Second</option>
<option value="third">Third</option>
</select>
<input type="submit" value="Submit the form"/>
</form>
process.php
<?php
$option = isset($_POST['taskOption']) ? $_POST['taskOption'] : false;
if ($option) {
echo htmlentities($_POST['taskOption'], ENT_QUOTES, "UTF-8");
} else {
echo "task option is required";
exit;
}
Answered by Ryan
Solution #3
You can also do it this way:
<?php
if(isset($_POST['select1'])){
$select1 = $_POST['select1'];
switch ($select1) {
case 'value1':
echo 'this is value1<br/>';
break;
case 'value2':
echo 'value2<br/>';
break;
default:
# code...
break;
}
}
?>
<form action="" method="post">
<select name="select1">
<option value="value1">Value 1</option>
<option value="value2">Value 2</option>
</select>
<input type="submit" name="submit" value="Go"/>
</form>
Answered by Dan Costinel
Solution #4
<select name="taskOption">
<option value="first">First</option>
<option value="second">Second</option>
<option value="third">Third</option>
</select>
$var = $_POST['taskOption'];
Answered by Jeroen Vannevel
Solution #5
It depends on whether the method of the form in which the select is contained is “get” or “post.”
The value of the choose will be stored in the super global array $_GET[‘taskOption’] if the form method=”get”> is used.
If the form method=”post”> is used, the value of the choose will be stored in the $_POST[‘taskOption’] super global array.
To save it as a variable, do the following:
$option = $_POST['taskOption']
The PHP handbook is a nice location to look for further information: http://php.net/manual/en/tutorial.forms.php
Answered by user2465080
Post is based on https://stackoverflow.com/questions/17139501/using-post-to-get-select-option-value-from-html