如何在switch语句中使用变量名?

时间:2013-04-28 01:21:02

标签: php switch-statement

我可以以某种方式简化下面的代码并只使用一个switch语句吗?看起来我需要第三个开关,所以如果可能的话,只使用一个就很棒。

    $input_separator= $_REQUEST['input_separator'];

    switch ($input_separator) {  
        case "new_line":
            $input_separator="\n";
            break;
        case "comma":
            $input_separator=",";
            break;
        case "none":
            $input_separator="";
            break;
    }



    $output_separator= $_REQUEST['output_separator'];

    switch ($output_separator) {
        case "new_line":
            $output_separator="\n";
            break;
        case "comma":
            $output_separator=",";
            break;
        case "none":
            $output_separator="";
            break;
    }

2 个答案:

答案 0 :(得分:2)

看起来您不需要任何 switch语句:

$input_separator = $_REQUEST['input_separator'] == "new_line" ? "\n" : "";
$output_separator = $_REQUEST['output_separator'] == "new_line" ? "\n" : "";

编辑:试试这个:

$separators = Array(
    "new_line"=>"\n",
    "comma"=>",",
    "none"=>""
);
$input_separator = $separators[$_REQUEST['input_separator']];
$output_separator = $separators[$_REQUEST['output_separator']];

答案 1 :(得分:1)

为什么不使用简单的功能?

function convert_seperator($seperator){
    $ret = '';
    switch ($seperator) {  
        case "new_line":
            $ret = "\n"; // or $ret = PHP_EOL;
            break;
        case "comma":
            $ret = ",";
            break;
        case "none":
            $ret = "";
            break;
        default:
            exit('Invalid seperator');
    }
    return $ret;
}
$input_separator = convert_seperator($_REQUEST['input_separator']);
$output_separator = convert_seperator($_REQUEST['output_separator']);