2013-04-28 7 views
0

어떻게 든 아래 코드를 단순화하고 switch 문 하나만 사용할 수 있습니까? 가능한 경우에만 하나만 사용하는 것이 좋을 것입니다.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; 
    } 
+0

스위치()는 SINGLE 값과 잠재적 인 일치 값 목록을 비교하는 데 사용됩니다. 그것은 if() else if() else if() else if()'를 사용하는 더 좋은 방법 일뿐입니다. 두 개의 값을 비교하기를 원할 수도 있지만 아주 추악하고 많은 진단하기 어려운 버그가 있습니다. –

답변

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']]; 
+0

좋은 지적 :-) 제 질문을 업데이트했습니다. 쉼표 스위치가 추가되었습니다. – Radek

+0

답변 편집을 참조하십시오. –

+0

위대한 대답, 왜 그것에 대해 생각하지 않았습니까? – Radek

1

이 왜 간단한 기능을 사용하지 않는를?

관련 문제