Development Tip

케이스 당 여러 값으로 PHP 전환을 수행하는 가장 좋은 방법은 무엇입니까?

yourdevel 2020. 11. 11. 20:47
반응형

케이스 당 여러 값으로 PHP 전환을 수행하는 가장 좋은 방법은 무엇입니까?


이 PHP switch 문을 어떻게 수행합니까?

또한 이것들은 훨씬 더 작은 버전이며, 내가 만들어야하는 1에는 더 많은 값이 추가 될 것입니다.

버전 1 :

switch ($p) { 
    case 'home': 
    case '': 
        $current_home = 'current';
    break; 

    case 'users.online': 
    case 'users.location': 
    case 'users.featured': 
    case 'users.new': 
    case 'users.browse': 
    case 'users.search': 
    case 'users.staff': 
        $current_users = 'current';
    break;

    case 'forum': 
        $current_forum = 'current';
    break; 
} 

버전 2 :

switch ($p) { 
    case 'home': 
        $current_home = 'current';
    break; 

    case 'users.online' || 'users.location' || 'users.featured' || 'users.browse' || 'users.search' || 'users.staff': 
        $current_users = 'current';
    break;

    case 'forum': 
        $current_forum = 'current';
    break; 
} 

업데이트-테스트 결과

10,000 번의 반복으로 속도 테스트를 실행했습니다.

Time1 : 0.0199389457703 // If 문
Time2 : 0.0389049446106 // 문 전환
Time3 : 0.106977939606 // 배열


알 수없는 문자열이 있고 일치하는 다른 문자열 을 파악해야하는 상황에서 항목을 더 추가해도 느려지지 않는 유일한 해결책은 배열을 사용하는 것입니다. 키로 가능한 문자열. 따라서 스위치를 다음으로 교체 할 수 있습니다.

// used for $current_home = 'current';
$group1 = array(
        'home'  => True,
        );

// used for $current_users = 'current';
$group2 = array(
        'users.online'      => True,
        'users.location'    => True,
        'users.featured'    => True,
        'users.new'         => True,
        'users.browse'      => True,
        'users.search'      => True,
        'users.staff'       => True,
        );

// used for $current_forum = 'current';
$group3 = array(
        'forum'     => True,
        );

if(isset($group1[$p]))
    $current_home = 'current';
else if(isset($group2[$p]))
    $current_users = 'current';
else if(isset($group3[$p]))
    $current_forum = 'current';
else
    user_error("\$p is invalid", E_USER_ERROR);

이것은.만큼 깔끔해 보이지는 않지만 switch(), 깔끔하게 유지하기 위해 함수와 클래스의 작은 라이브러리를 작성하는 것을 포함하지 않는 유일한 빠른 솔루션입니다. 배열에 항목을 추가하는 것은 여전히 ​​매우 쉽습니다.


버전 2가 작동하지 않습니다 !!

case 'users.online' || 'users.location' || ...

다음과 정확히 동일합니다.

case True:

그것은 case어떤 값을 선택한 것입니다 $p하지 않는 한, $p빈 문자열입니다.

||case안에 특별한 의미 가 없으며, $p각 문자열 과 비교하지 않고, 그렇지 않은지 확인하는 것 False입니다.


이러한 많은 값을 배열에 넣고 배열을 쿼리합니다. switch-case는 문자열 변수가 조건으로 사용될 때 달성하려는 기본 의미를 숨기는 것처럼 보이므로 읽고 이해하기가 더 어렵습니다. :

$current_home = null;
$current_users = null;
$current_forum = null;

$lotsOfStrings = array('users.online', 'users.location', 'users.featured', 'users.new');

if(empty($p)) {
    $current_home = 'current';
}

if(in_array($p,$lotsOfStrings)) {
    $current_users = 'current';
}

if(0 === strcmp('forum',$p)) {
    $current_forum = 'current';
}

경우 누구 매우 비 표준입니다 - 다른 사람이 코드를 유지하기 위해 이제까지했다, 그들은 거의 확실 버전 2에 더블 테이크를 할 것이다.

저는 버전 1을 고수 할 것입니다.하지만 그 자체의 문 블록이없는 케이스 문 // fall through옆에 명시적인 주석 이 있어야 실제로 통과하려는 의도임을 나타내야합니다. 사건을 다르게 처리하려고했는데 잊었거나 뭔가요.


완전성을 위해 깨진 "버전 2"논리를 작동하는 switch 문으로 대체 할 수 있으며 다음과 같이 속도와 명확성을 위해 배열을 사용할 수도 있습니다.

// $ current_home = 'current';
$ home_group = 배열 ​​(
    '집'=> 사실,
);

// $ current_users = 'current';
$ user_group = 배열 ​​(
    'users.online'=> 사실,
    'users.location'=> 참,
    'users.featured'=> 참,
    'users.new'=> 참,
    'users.browse'=> 참,
    'users.search'=> 참,
    'users.staff'=> 참,
);

// $ current_forum = 'current';
$ forum_group = 배열 ​​(
    '포럼'=> 사실,
);

switch (true) {
    케이스 isset ($ home_group [$ p]) :
        $ current_home = '현재';
        단절;
    케이스 isset ($ user_group [$ p]) :
        $ current_users = '현재';
        단절;
    case isset ($ forum_group [$ p]) :
        $ current_forum = '현재';
        단절;
    기본:
        user_error ( "\ $ p는 유효하지 않습니다", E_USER_ERROR);
}    

아직 언급되지 않은 다른 아이디어 :

switch(true){ 
  case in_array($p, array('home', '')): 
    $current_home = 'current'; break;

  case preg_match('/^users\.(online|location|featured|new|browse|search|staff)$/', $p):
    $current_users = 'current'; break;

  case 'forum' == $p:
    $current_forum = 'current'; break; 
}

누군가는 아마도 # 2의 가독성 문제에 대해 불평 할 것입니다. 그러나 나는 그런 코드를 상속하는 데 아무런 문제가 없을 것입니다.


버전 1은 확실히 눈에 더 쉽고, 의도가 더 명확하며 케이스 조건을 추가하기가 더 쉽습니다.

두 번째 버전을 시도한 적이 없습니다. 많은 언어에서 각 케이스 레이블이 상수 표현식으로 평가되어야하므로 컴파일조차되지 않습니다.


I definitely prefer Version 1. Version 2 may require less lines of code, but it will be extremely hard to read once you have a lot of values in there like you're predicting.

(Honestly, I didn't even know Version 2 was legal until now. I've never seen it done that way before.)


No version 2 doesn't actually work but if you want this kind of approach you can do the following (probably not the speediest, but arguably more intuitive):

switch (true) {
case ($var === 'something' || $var === 'something else'):
// do some stuff
break;
}


maybe

        switch ($variable) {
        case 0:
            exit;
            break;
        case (1 || 3 || 4 || 5 || 6):
            die(var_dump('expression'));
        default:
            die(var_dump('default'));
            # code...
            break;
    }

I think version 1 is the way to go. It is a lot easier to read and understand.


if( in_array( $test, $array1 ) )
{
    // do this
}
else if( stristr( $test, 'commonpart' ) )
{
    // do this
}
else
{
    switch( $test )
    {
        case 1:
            // do this
            break;
        case 2:
            // do this
            break;
        default:
            // do this
            break;
    }
}

Switch in combination with variable variables will give you more flexibility:

<?php
$p = 'home'; //For testing

$p = ( strpos($p, 'users') !== false? 'users': $p);
switch ($p) { 
    default:
        $varContainer = 'current_' . $p; //Stores the variable [$current_"xyORz"] into $varContainer
        ${$varContainer} = 'current'; //Sets the VALUE of [$current_"xyORz"] to 'current'
    break;

}
//For testing
echo $current_home;
?>

To learn more, checkout variable variables and the examples I submitted to php manual:
Example 1: http://www.php.net/manual/en/language.variables.variable.php#105293
Example 2: http://www.php.net/manual/en/language.variables.variable.php#105282

PS: This example code is SMALL AND SIMPLE, just the way I like it. It's tested and works too


Nowadays you can do...

switch ([$group1, $group2]){
    case ["users", "location"]:
    case ["users", "online"]:
        Ju_le_do_the_thing();
        break;
    case ["forum", $group2]:
        Foo_the_bar();
        break;
}

참고URL : https://stackoverflow.com/questions/1309728/best-way-to-do-a-php-switch-with-multiple-values-per-case

반응형