Php 如何在switch语句中使用变量名?
我可以简化下面的代码,只使用一个switch语句吗?看起来我需要第三个开关,所以如果可能的话,最好只使用一个Php 如何在switch语句中使用变量名?,php,switch-statement,Php,Switch Statement,我可以简化下面的代码,只使用一个switch语句吗?看起来我需要第三个开关,所以如果可能的话,最好只使用一个 $input_separator= $_REQUEST['input_separator']; switch ($input_separator) { case "new_line": $input_separator="\n"; break; case "comma":
$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;
}
看起来您不需要任何
开关
语句:
$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']];
看起来您不需要任何
开关
语句:
$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']];
为什么不使用简单函数呢
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']);
为什么不使用简单函数呢
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']);
switch()用于将单个值与潜在匹配值列表进行比较。这只是一种更好的方法,可以执行
if()else if()else if()else if()
。如果您想比较两个值,您可以,但它会变得非常难看,并且会受到许多难以诊断的错误的影响。switch()用于将单个值与潜在匹配值列表进行比较。这只是一种更好的方法,可以执行if()else if()else if()else if()
。如果你想比较两个值,你可以,但它会变得非常难看,并受到许多难以诊断的错误的影响。伟大的答案,我为什么不考虑一下呢?别担心,我花了一段时间才发现我可以做到:p真正的节省空间!回答得很好,为什么我没想到呢?别担心,我花了一段时间才发现我可以做到:p真的节省了空间!