Coder Perfect

choose the HTML value for the option


I use select as below:

<select name="taskOption">

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>

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>
  <input type="submit" value="Submit the form"/>


   $option = isset($_POST['taskOption']) ? $_POST['taskOption'] : false;
   if ($option) {
      echo htmlentities($_POST['taskOption'], ENT_QUOTES, "UTF-8");
   } else {
     echo "task option is required";

Answered by Ryan

Solution #3

You can also do it this way:

    $select1 = $_POST['select1'];
    switch ($select1) {
        case 'value1':
            echo 'this is value1<br/>';
        case 'value2':
            echo 'value2<br/>';
            # code...

<form action="" method="post">
    <select name="select1">
        <option value="value1">Value 1</option>
        <option value="value2">Value 2</option>
    <input type="submit" name="submit" value="Go"/>

Answered by Dan Costinel

Solution #4

<select name="taskOption">
      <option value="first">First</option>
      <option value="second">Second</option>
      <option value="third">Third</option>

$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:

Answered by user2465080

Post is based on