Hamed mohamad nejad
Hamed mohamad nejad

Reputation: 9

Get selected key/value of a select box using php

how can I get the selected key and value of a HTML select box using php?

<select>
    <option value="KEY">VALUE</option>
</select>

php code ?

Upvotes: 0

Views: 5959

Answers (6)

Shadab Mehdi
Shadab Mehdi

Reputation: 653

Let's say you have form like this

<select name="country">
    <option value="IN_India">India</option>
    <option value="CN_China">China</option>
    <option value="AE_UAE">UAE</option>
</select>

Upon submitting it, your $_POST would look something like this

print_r($_POST);

Array
(
    [country] => IN_India
}

Now explde your $_POST data and fetch values like this

$data = explode('_', filter_input(INPUT_POST, 'country'));
print_r($data);

Array
(
    [0] => IN
    [1] => India
)

Upvotes: 0

Jopie
Jopie

Reputation: 332

Using PHP, you could use this:

Put Key and Value as POST data, delimited with a symbol, for example '/'.

HTML:

<select name="myselect">
    <option value="KEY/VALUE">VALUE</option>
</select>

Then in PHP, separate that key with explode() function.

PHP:

$pair = explode("/", $_POST["myselect"]);

$key   = $pair[0];
$value = $pair[1];

print "Key: $key<br />";
print "Value: $value<br />";

Upvotes: 0

Webeng
Webeng

Reputation: 7143

page1.html:

<form action="page2.php" name='add' method="post">
<select name="foo">
    <option value="my_value">my_value</option>
</select>
<input type='submit' name='submit'/>
</form>

page2.php:

<?php
$result = $_POST['foo'];
echo "result = ".$result."<br>";//output: result = my_value
?>

Upvotes: 0

Meathanjay
Meathanjay

Reputation: 2073

Name of the select is the key and option is the value.

<select name="KEY">
  <option value="VALUE">VALUE</option>
  <option value="VALUE_2">VALUE</option>
</select>

On submit you will get a KEY => VALUE pair in $_GET or $_POST (whatever you use to handle the request)

Upvotes: 0

Pupil
Pupil

Reputation: 23978

With PHP, it is not straight forward.

However, with use of array you can achieve it.

Take and array of all options in a common function:

$options = array();
$options[1] = 'one';
$options[2] = 'two';
$options[3] = 'three';

Display drop down like this:

<select name="opt">
<option value=""></option>
<?php
if (! empty($options)) {
 foreach ($options as $key => $val)  {
?>
<option value="<?php echo $key;?>"><?php echo $val;?></option>
<?php
 }
}
?>
</select>

And where the form is posted, again get the array.

//$options : fetch from common function.

if (isset($_POST['opt'])) {
 echo "key: " . $_POST['opt'];
 echo "<br/>";
 echo "value: " . isset($options[$_POST['opt']]) ? $options[$_POST['opt']] : '';
}

Upvotes: 3

Fil
Fil

Reputation: 8873

You must do like this

<form class="" action="receiver.php" method="post">
  <select name="mykey">
      <option value="KEY">VALUE</option>
  </select>      
</form>

In your receiver.php do in this example

$keys = $_POST['mykey'];

Upvotes: 0

Related Questions