简体   繁体   中英

PHP Dropdown List variable

I am trying to have a drop down menu where you can choose from 3 options. I've got the following code, but I can't seem to get my third option to work. Any ideas?

        $_POST['faction'] = ($_POST['faction'] == "s")? "S" : "K";

I want to add a third option which is "R" and I can't get it to work.

Ideas please?

Although adding another ternary statement to your statement is possible I think it will affect the code readability.

Using array will make this simpler.

$option_array = array('r' => 'R', 's' => 'S', 'k' => 'K');

if (array_key_exists($_POST['faction'])) { 
    $_POST['faction'] = $option_array[$_POST['faction']]
}

You could choose to add the array_key_exists to make sure you are not updating $_POST['faction'] if $_POST['faction'] contains other values, but this is your choice.

Another approach similar to yours with multiple ternary operations:

$_POST['faction'] = ($_POST['faction'] == "s") ? ($_POST['faction'] == "r" ? "R" : "S") : "K";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM