비교 연산자

이름에서 알 수 있듯이 비교 연산자를 사용하면 두 값을 비교할 수 있습니다. 다양한 유형 관련 비교의 예를 보여주기 때문에 자료형 비교 테이블을 보는 데 관심이 있을 수도 있습니다.

비교 연산자

Example Name Result
$a == $b Equal true if $a is equal to $b after type juggling.
$a === $b Identical true if $a is equal to $b, and they are of the same type.
$a != $b Not equal true if $a is not equal to $b after type juggling.
$a <> $b Not equal true if $a is not equal to $b after type juggling.
$a !== $b Not identical true if $a is not equal to $b, or they are not of the same type.
$a < $b Less than true if $a is strictly less than $b.
$a > $b Greater than true if $a is strictly greater than $b.
$a <= $b Less than or equal to true if $a is less than or equal to $b.
$a >= $b Greater than or equal to true if $a is greater than or equal to $b.
$a <=> $b Spaceship An int less than, equal to, or greater than zero when $a is less than, equal to, or greater than $b, respectively.

두 피연산자가 모두 숫자 문자열이거나 한 피연산자가 숫자이고 다른 하나가 숫자 문자열이면 비교가 숫자로 수행됩니다. 이 규칙은 switch 문에도 적용됩니다. 비교가 !== 또는 !==일 때는 유형과 값을 비교해야 하므로 유형 변환이 발생하지 않습니다.

경고

PHP 8.0.0 이전에는 문자열이 숫자 또는 숫자 문자열과 비교되면 비교를 수행하기 전에 문자열이 숫자로 변환되었습니다. 이는 다음 예에서 볼 수 있듯이 놀라운 결과를 초래할 수 있습니다.

                    
  <?php
  var_dump(0 == "a");
  var_dump("1" == "01");
  var_dump("10" == "1e1");
  var_dump(100 == "1e2");

  switch ("a") {
  case 0:
      echo "0";
      break;
  case "a":
      echo "a";
      break;
  }
  ?>
                    
                  

PHP 7에서 위 예제의 출력:

bool(true)
bool(true)
bool(true)
bool(true)
0
                  

PHP 8에서 위 예제의 출력:

bool(false)
bool(true)
bool(true)
bool(true)
a
                  
                  
<?php
// Integers
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1

// Floats
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1

// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1

echo "a" <=> "aa"; // -1
echo "zz" <=> "aa"; // 1

// Arrays
echo [] <=> []; // 0
echo [1, 2, 3] <=> [1, 2, 3]; // 0
echo [1, 2, 3] <=> []; // 1
echo [1, 2, 3] <=> [1, 2, 1]; // 1
echo [1, 2, 3] <=> [1, 2, 4]; // -1

// Objects
$a = (object) ["a" => "b"];
$b = (object) ["a" => "b"];
echo $a <=> $b; // 0

$a = (object) ["a" => "b"];
$b = (object) ["a" => "c"];
echo $a <=> $b; // -1

$a = (object) ["a" => "c"];
$b = (object) ["a" => "b"];
echo $a <=> $b; // 1

// not only values are compared; keys must match
$a = (object) ["a" => "b"];
$b = (object) ["b" => "b"];
echo $a <=> $b; // 1

?>
                  
                

다양한 유형에 대해 다음 표에 따라(순서대로) 비교합니다.

다양한 유형과의 비교

Type of Operand 1 Type of Operand 2 Result
null or string string Convert null to "", numerical or lexical comparison
bool or null anything Convert both sides to bool, false < true
object object Built-in classes can define its own comparison, different classes are uncomparable, same class see Object Comparison
string, resource, int or float string, resource, int or float Translate strings and resources to numbers, usual math
array array Array with fewer members is smaller, if key from operand 1 is not found in operand 2 then arrays are uncomparable, otherwise - compare value by value (see following example)
object anything object is always greater
array anything array is always greater

예제 #1 부울/널 비교

                  
<?php
// Bool and null are compared as bool always
var_dump(1 == TRUE);  // TRUE - same as (bool)1 == TRUE
var_dump(0 == FALSE); // TRUE - same as (bool)0 == FALSE
var_dump(100 < TRUE); // FALSE - same as (bool)100 < TRUE
var_dump(-10 < FALSE);// FALSE - same as (bool)-10 < FALSE
var_dump(min(-100, -10, NULL, 10, 100)); // NULL - (bool)NULL < (bool)-100 is FALSE < TRUE
?>
                  
                

예제 #2 Transcription of standard array comparison

                  
<?php
// Arrays are compared like this with standard comparison operators
function standard_array_compare($op1, $op2)
{
    if (count($op1) < count($op2)) {
        return -1; // $op1 < $op2
    } elseif (count($op1) > count($op2)) {
        return 1; // $op1 > $op2
    }
    foreach ($op1 as $key => $val) {
        if (!array_key_exists($key, $op2)) {
            return null; // uncomparable
        } elseif ($val < $op2[$key]) {
            return -1;
        } elseif ($val > $op2[$key]) {
            return 1;
        }
    }
    return 0; // $op1 == $op2
}
?>
                  
                
경고
부동 소수점 숫자 비교

부동 소수점이 내부적으로 표현되는 방식 때문에 두 부동 소수점이 같은지 테스트해서는 안 됩니다.

자세한 내용은 float 문서를 참조하십시오.

기타

삼항 연산자

또 다른 조건 연산자는 "?:"(또는 삼항) 연산자입니다.

예제 #3 기본값 할당

                  
<?php
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];

// The above is identical to this if/else statement
if (empty($_POST['action'])) {
    $action = 'default';
} else {
    $action = $_POST['action'];
}

?>
                  
                

표현식 (expr1) ? (expr2) : (expr3)은 expr1이 true로 평가되면 expr2로 평가되고 expr1이 false로 평가되면 expr3으로 평가됩니다.

삼항 연산자의 중간 부분을 생략할 수 있습니다. 식 expr1 ?: expr3은 expr1이 true로 평가되면 expr1을 반환하고 그렇지 않으면 expr3을 반환합니다.

참고: 삼항 연산자는 표현식이며 변수로 평가되지 않고 표현식의 결과로 평가된다는 점에 유의하십시오. 참조로 변수를 반환하려는지 여부를 아는 것이 중요합니다. 참조에 의한 반환 함수에서 명령문 return $var == 42 ? $a : $b;은 작동하지 않고 경고가 발생합니다.

메모:

삼항 표현식을 "스태킹"하지 않는 것이 좋습니다. 단일 표현식 내에서 두 개 이상의 괄호로 묶이지 않은 삼항 연산자를 사용할 때 PHP의 동작은 다른 언어에 비해 명확하지 않습니다. 실제로 PHP 8.0.0 이전에는 삼항 표현식이 대부분의 다른 프로그래밍 언어처럼 오른쪽 결합 대신 왼쪽 결합으로 평가되었습니다. 왼쪽 연관성에 의존하는 것은 PHP 7.4.0부터 더 이상 사용되지 않습니다. PHP 8.0.0부터 삼항 연산자는 비연관적입니다.

예제 #4 명확하지 않은 삼항 동작

                    
  <?php
  // on first glance, the following appears to output 'true'
  echo (true ? 'true' : false ? 't' : 'f');

  // however, the actual output of the above is 't' prior to PHP 8.0.0
  // this is because ternary expressions are left-associative

  // the following is a more obvious version of the same code as above
  echo ((true ? 'true' : false) ? 't' : 'f');

  // here, one can see that the first expression is evaluated to 'true', which
  // in turn evaluates to (bool)true, thus returning the true branch of the
  // second ternary expression.
  ?>
                    
                  
널 병합 연산자

"??"가 더 존재합니다. (또는 null 병합) 연산자.

예제 #5 기본값 할당

                  
<?php
// Example usage for: Null Coalesce Operator
$action = $_POST['action'] ?? 'default';

// The above is identical to this if/else statement
if (isset($_POST['action'])) {
    $action = $_POST['action'];
} else {
    $action = 'default';
}

?>
                  
                

(expr1) ?? (expr2)null이면 expr2로 평가되고 그렇지 않으면 expr1로 평가됩니다. 특히 이 연산자는 isset()처럼 좌변 값이 존재하지 않는 경우 알림이나 경고를 표시하지 않습니다. 이것은 배열 키에서 특히 유용합니다.

참고: null 병합 연산자는 표현식이며 변수로 평가되지 않고 표현식의 결과로 평가된다는 점에 유의하십시오. 참조로 변수를 반환하려는지 여부를 아는 것이 중요합니다. 참조에 의한 반환 함수내에서 명령문 return $foo ?? $bar;은 작동하지 않고 경고가 발생합니다.

참고

null 병합 연산자를 사용하면 간단한 중첩이 가능합니다.

예제 #6 중첩 null 병합 연산자

                    
  <?php

  $foo = null;
  $bar = null;
  $baz = 1;
  $qux = 2;

  echo $foo ?? $bar ?? $baz ?? $qux; // outputs 1

  ?>