php switch case:如果我们有30个选项,我们是否必须创建30个if语句或者是否有更简单的方法?

时间:2012-10-30 14:28:12

标签: php arrays drop-down-menu switch-statement

我在下面找到了这个代码并且它非常适合我想要的但是我有30多个选项我还能做些什么来缩短代码?

<html>
<body>
    <form method="post" action="?">
    <select name="dropdown">
    <option value="Jehzeel1">Jehzeel1</option>
    <option value="Jehzeel2">Jehzeel2</option>
    <option value="Jehzeel3">Jehzeel3</option>
    </select>
    <input type="submit" value="submit">
    </form>
</body>
</html>



    <?php
    switch ($_POST['dropdown'])  { 

        case "Jehzeel1":
         echo "Jehzeel likes apples";
        break;

        case "Jehzeel2":
         echo "Jehzeel likes bananas";
        break;

        case "Jehzeel3":
         echo "Jehzeel likes oranges";
        break;

    ?>

4 个答案:

答案 0 :(得分:4)

创建映射数组更容易:

$map = array(
    'Jehzeel2' => 'Jehzeel likes bananas';
    'Jehzeel3' => 'Jehzeel likes oranges';
);

echo $map[$_POST['dropdown']];

虽然你可能想要对你的代码结构三思而后行,但这看起来是一种不好的做法。

简短方法:

<?php
$fruits = array('apples', 'oranges', 'bananas');
?>
<form method="post">
    <select name="dropdown">
    <?php foreach ($fruits as $fruit) : ?>
        <option value="<?php echo $fruit ?>"><?php echo $fruit ?></option>
    <?php endforeach; ?>
    </select>
    <input type="submit" value="submit" />
</form>
<?php
if (in_array($_POST['dropdown'], $fruits)) {
    echo 'Jehzeel likes ' . $_POST['dropdown'];
}
?>

修改

您可以通过稍微更改数组和if语句来使用网址:

$urls = array('url1' => 'http://www.facebook.com/', 'url2' => 'http://www.google.com/', 'url3' => 'http://www.yahoo.com/');

if (isset($urls[$_POST['dropdown']])) {
    echo 'URL: ' . $urls[$_POST['dropdown']];
}

答案 1 :(得分:2)

考虑将选项的值更改为:

<select name="dropdown">
    <option value="apples">Jehzeel1</option>
    <option value="bananas">Jehzeel2</option>
    <option value="oranges">Jehzeel3</option>
</select>

然后只需在您的PHP代码中:

$valid_fruits = array("apples", "bananas", "oranges");

$fruit = $_POST['dropdown'];
if(in_array($fruit,$valid_fruit))
    echo "Jehzeel likes $fruit"

我希望它有所帮助。干杯

答案 2 :(得分:2)

您可以使用数组作为键,文本作为值:

 // array of key/value pairs
 $text = array(
     "Jehzeel1" => "apples",
     "Jehzeel2" => "bananas",
     "Jehzeel3" => "oranges",
 );
 // create your key from the post value, make sure it is actually set
 $key = isset($_POST['dropdown']))? $_POST['dropdown'] : "";
 // echo the value based on the key, if the key exists
 $value = (array_key_exists($key, $text))? $text[$key] : "nothing";
 // assuming all the text starts with "Jehzeel likes" you can sprintf the value
 echo sprintf("Jehzeel likes %s.", $value);

答案 3 :(得分:0)

使用您的选项创建数组

$DropdownLabels = array (
    'dropdown1' => 'Dropdown1 Long Label',
    'dropdown2' => 'Dropdown2 Long Label',
    // ...,
);

然后使用$DropdownLabels[$_POST['dropdown']]并测试array_key_exists($_POST['dropdown'], $DropdownLabels)是否存在。