티스토리 뷰

반응형

간단한 구문을 처리할 때 경우에 따라 if else 보다는 간편한 ?:(3항 연산자)를 사용할 때가 있다.

얼마 전 PHP 8.0이 등장하면서 switch case 보다 가벼운 어떻게 보면 switch case의 3항 연산자 match가 추가되었다.

match에 대해 알아보자.

 

※ 참고로 match는 PHP 8.0 이상 버전에서 사용 가능하다.

 

// 3항 연산자에 대한 정보는 따로 정리한 포스팅을 참고해주세요.

https://heavening.tistory.com/106

 

PHP 물음표와 콜론 3항 연산자 (조건부 연산자) ?:

(이미 8.2까지 나왔지만...) 얼마 전 PHP 8.0이 릴리즈와 함께 추가된 match에 대해 포스팅을 하려하는데 3항 연산자(또는 조건부 연산자, 이하 '3항 연산자')를 잠깐 언급하려고 하다가 3항 연산자에

heavening.tistory.com

 

예제를 통해 사용법부터 알아봅시다.

<?php
    $value = "1";
    switch($value) {
        case "1" : $result = "this is 1"; break;
        case "2" : $result = "this is 2"; break;
        default : $result = "what's this?"; break;
    }
    echo $result; // this is 1
?>

<?php
    $value = "1";
    $result = match($value) {
        "1" => "this is 1",
        "2" => "this is 2",
        default => "what's this?",
    };
    echo $result; // this is 1
?>
<?php
    $value = "orange";
    switch($value) {
        case "apple" :
        case "orange" :
        case "strawberry" :
            $result = "fruit";
            break;
        default :
            $result = "unknown";
            break;
    }
    echo $result; // fruit
?>

<?php
    $value = "orange";
    $result = match($value) {
        "apple", "orange", "strawberry" => "fruit",
        default => "unknown",
    };
    echo $result; // fruit
?>

위와 같이 switch 대신 match를 사용하면 코드가 간소화되고 무엇보다 가독성이 좋아진다.

물론 조건별로 복잡한 로직을 입력하려면 switch를 사용해야 한다.

하지만 조건에 따라 단순히 일정 수식이나 값을 리턴하는 것이라면 match가 좋을 것이다.

 

switch와 match에는 큰 차이가 하나 있는데

조건을 충족 시킬 때 switch case와 달리 '=='가 아닌 '==='로 조건을 성립시켜야 결과가 발동된다.

 

아래 예제를 보자.

<?php
    $value = true;
    switch($value) {
        case "1" : $result = "string"; break;
        case 1 : $result = "int"; break;
        case true : $result = "bool"; break;
        default : $result = "unknown"; break;
    }
    
    echo $result; // string
?>

<?php
    $value = true;
    $result = match($value) {
        "1" => "string",
        1 => "int",
        true => "bool",
        default => "unknown",
    };
    
    echo $result; // bool
?>

 

 

 

 

 

 

 

 

 

 

 

 

반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함