PHP Velho Oeste 2024

비교 연산자

비교 연산자는 이름 그대로 두 값을 비교하도록 합니다. 자료형 비교표에서 다양한 자료형 관련 비교의 예제를 확인해 볼 수 있습니다.

비교 연산자
예제 이름 결과
$a == $b Equal $a와 $b가 같으면 TRUE.
$a === $b Identical $a와 $b가 같고, 같은 자료형이면 TRUE. (PHP 4에서 추가)
$a != $b Not equal $a가 $b와 같지 않으면 TRUE.
$a <> $b Not equal $a가 $b와 같지 않으면 TRUE.
$a !== $b Not identical $a가 $b와 같지 않거나, 같은 자료형이 아니면 TRUE. (PHP 4에서 추가)
$a < $b Less than $a가 $b보다 작으면 TRUE.
$a > $b Greater than $a가 $b보다 크면 TRUE.
$a <= $b Less than or equal to $a가 $b보다 작거나 같으면 TRUE.
$a >= $b Greater than or equal to $a가 $b보다 크거나 같으면 TRUE.

정수를 문자열과 비교하면, 문자열이 수로 변환됩니다. 두개의 수 문자열을 비교하면, 정수로 비교됩니다. 이 규칙은 switch 구문에도 적용됩니다.

<?php
var_dump
(== "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true
var_dump("1" == "1e0"); // 1 == 1 -> true

switch ("a") {
case 
0:
    echo 
"0";
    break;
case 
"a"// never reached because "a" is already matched with 0
    
echo "a";
    break;
}
?>

다양한 자료형에 대해서, 비교는 다음 표에 따라 이루어집니다. (순서대로)

다양한 자료형 비교
연산수 1의 자료형 연산수 2의 자료형 결과
null이나 string string NULL을 ""로 변환, 수치나 어휘 비교
bool이나 null anything bool로 변환, FALSE < TRUE
object object 내장 클래스는 자신의 비교 함수를 정의할 수 있습니다. 다른 클래스는 비교할 수 없고, 같은 클래스는 배열과 같은 방식으로 프로퍼티를 비교합니다(PHP 4). PHP 5는 자체의 해석법을 가지고 있습니다.
string, resource, number string, resource, number 문자열과 자원을 수로 변환하여, 일반적인 수학
array array 적은 멤버를 가진 배열이 작고, 연산수 1의 키가 연산수 2에서 발견되지 않으면 배열을 비교할 수 없고, 그렇지 않으면 - 값대 값으로 비교(아래 예제를 참고)
array 모두 array가 항상 큽니다
object 모두 object가 항상 큽니다

Example #1 표준 배열 비교의 모사

<?php
// 표준 비교 연산자로 배열은 이렇게 비교합니다
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
}
?>

참고: strcasecmp(), strcmp(), 배열 연산자, 매뉴얼 자료형 섹션.

삼항 연산자

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

Example #2 기본값 할당하기

<?php
// 사용 예제: 삼항 연산자
$action = (empty($_POST['action'])) ? 'default' $_POST['action'];

// 위 예제는 다음의 if/else 구문과 동일합니다
if (empty($_POST['action'])) {
    
$action 'default';
} else {
    
$action $_POST['action'];
}

?>
(expr1) ? (expr2) : (expr3) 표현은 expr1TRUE이면 expr2로 평가되고, expr1FALSE이면 expr3로 평가됩니다.

PHP 5.3부터, 삼항 연산자의 중간 부분을 비울 수 있습니다. 표현식 expr1 ?: expr3expr1TRUE이면 expr1, 아니면 expr3를 반환합니다.

Note: 삼항 연산자는 구문이므로, 변수로 평가되지 않고 구문의 결과로 평가되는 점에 주의하십시오. 이 점은 참조로 변수를 반환할 때 중요합니다. 그러므로 참조로 반환하는 함수에서 return $var == 42 ? $a : $b; 구문은 작동하지 않고, 경고가 발생합니다.

Note:

삼항 연사자를 "쌓는" 일을 피하길 권합니다. 하나의 구문에서 하나를 초과하는 삼항 연산자를 사용할 때, PHP 작동은 명확하지 않습니다:

Example #3 명확하지 않은 삼항 작동

<?php
// 얼핏 보기에, 'true'를 출력할 것 같습니다
echo (true?'true':false?'t':'f');

// 그러나 위의 실제 출력은 't'입니다
// 이는 삼항 표현이 왼쪽에서 오른쪽으로 평가되기 때문입니다

// 다음이 위 코드와 동일한 더 명확한 버전입니다
echo ((true 'true' 'false') ? 't' 'f');

// 여기서, 첫 표현이 'true'로 평가되고, 이것이
// (bool)true로 전환되어 평가된 후, 두번째
// 삼항 표현의 true쪽을 반환합니다.
?>

add a note add a note

User Contributed Notes 13 notes

up
174
crazy888s at hotmail dot com
14 years ago
I couldn't find much info on stacking the new ternary operator, so I ran some tests:

<?php
echo 0 ?: 1 ?: 2 ?: 3; //1
echo 1 ?: 0 ?: 3 ?: 2; //1
echo 2 ?: 1 ?: 0 ?: 3; //2
echo 3 ?: 2 ?: 1 ?: 0; //3

echo 0 ?: 1 ?: 2 ?: 3; //1
echo 0 ?: 0 ?: 2 ?: 3; //2
echo 0 ?: 0 ?: 0 ?: 3; //3
?>

It works just as expected, returning the first non-false value within a group of expressions.
up
9
admin at zeros dot co dot id
1 year ago
Please be careful when you try to compare strings that have a plus sign `+` at the beginning (such as phone number, etc). When you use the Equal operator `==` PHP will ignore the plus sign. Use Identical operator `===` instead

Example:

$str1 = "62";
$str2 = "+62";

var_dump($str1 == $str2); // bool(true)
var_dump($str1 === $str2); // bool(false)
up
2
Hayley Watson
8 months ago
Between the "shortcut ternary" (aka "elvis") and "spaceship" operators, you can write some quite compact comparison functions for usort and its ilk.

If you want to sort an array of associative arrays by several different keys you can chain them in the same way that you can list column names in an SQL ORDER BY clause.

<?php
usort
($array, fn($a, $b) => $a['a'] <=> $b['a']
                         ?:
$b['b'] <=> $a['b']
                         ?:
$a['c'] <=> $b['c']);
?>
Will sort the array by column 'a', then by column 'b' descending, then by column 'c'; or in SQL-speak 'ORDER BY a, b DESC, c".
up
5
Sumon Mahmud
4 years ago
Extending from here: https://www.php.net/manual/en/language.operators.comparison.php#121907

$a = ['a' => 1, 'b' => 2, 'c' => 3, 'e' => 4];
$b = ['a' => 1, 'b' => 2, 'd' => 3, 'e' => 4];

echo $a > $b; // 0
echo $b > $a; // 0
echo $a <$b; // 0
echo $b < $a; // 0

If using spaceship operator then it is returning true like :

echo $a <=> $b; //1
echo $b <=> $a; //1
echo $a <=> $b; //1
echo $b <=> $a; //1
up
23
adam at caucho dot com
17 years ago
Note: according to the spec, PHP's comparison operators are not transitive.  For example, the following are all true in PHP5:

"11" < "a" < 2 < "11"

As a result, the outcome of sorting an array depends on the order the elements appear in the pre-sort array.  The following code will dump out two arrays with *different* orderings:

<?php
$a
= array(2,    "a""11", 2);
$b = array(2,    "11", "a"2);
sort($a);
var_dump($a);
sort($b);
var_dump($b);
?>

This is not a bug report -- given the spec on this documentation page, what PHP does is "correct".  But that may not be what was intended...
up
18
rshawiii at yahoo dot com
18 years ago
You can't just compare two arrays with the === operator
like you would think to find out if they are equal or not.  This is more complicated when you have multi-dimensional arrays.  Here is a recursive comparison function.

<?php
/**
* Compares two arrays to see if they contain the same values.  Returns TRUE or FALSE.
* usefull for determining if a record or block of data was modified (perhaps by user input)
* prior to setting a "date_last_updated" or skipping updating the db in the case of no change.
*
* @param array $a1
* @param array $a2
* @return boolean
*/
function array_compare_recursive($a1, $a2)
{
   if (!(
is_array($a1) and (is_array($a2)))) { return FALSE;}   
   
   if (!
count($a1) == count($a2))
      {
       return
FALSE; // arrays don't have same number of entries
     
}
     
   foreach (
$a1 as $key => $val)
   {
       if (!
array_key_exists($key, $a2))
           {return
FALSE; // uncomparable array keys don't match
             
}
       elseif (
is_array($val) and is_array($a2[$key]))  // if both entries are arrays then compare recursive
          
{if (!array_compare_recursive($val,$a2[$key])) return FALSE;
           }
       elseif (!(
$val === $a2[$key])) // compare entries must be of same type.
          
{return FALSE;
           }
   }
   return
TRUE; // $a1 === $a2
}
?>
up
7
Tahazzot
3 years ago
Very careful when reading PHP documentation, Here's a lot of miss information.

According to documentation, They say's (int) 0 == (string) "a" is true. But it is not in PHP 8.

var_dump(0 == "a"); // 0 == 0 -> true

Now In PHP 8 it's False.
up
13
bishop
17 years ago
When you want to know if two arrays contain the same values, regardless of the values' order, you cannot use "==" or "===".  In other words:

<?php
(array(1,2) == array(2,1)) === false;
?>

To answer that question, use:

<?php
function array_equal($a, $b) {
    return (
is_array($a) && is_array($b) && array_diff($a, $b) === array_diff($b, $a));
}
?>

A related, but more strict problem, is if you need to ensure that two arrays contain the same key=>value pairs, regardless of the order of the pairs.  In that case, use:

<?php
function array_identical($a, $b) {
    return (
is_array($a) && is_array($b) && array_diff_assoc($a, $b) === array_diff_assoc($b, $a));
}
?>

Example:
<?php
$a
= array (2, 1);
$b = array (1, 2);
// true === array_equal($a, $b);
// false === array_identical($a, $b);

$a = array ('a' => 2, 'b' => 1);
$b = array ('b' => 1, 'a' => 2);
// true === array_identical($a, $b)
// true === array_equal($a, $b)
?>

(See also the solution "rshawiii at yahoo dot com" posted)
up
2
gfilippakis at sleed dot gr
1 year ago
Please note that using the null coalescing operator to check properties on a class that has the __get magic method (without an __isset magic method) invokes the magic method.

For example:

<?php

class A
{
    public function
__get($property)
    {
        echo
'Called __get for ' . $property . PHP_EOL;
    }
}

$a = new A();

echo
'Trying null coalescing operator' . PHP_EOL;
$b = $a->test ?? 5;

echo
'Trying isset()' . PHP_EOL;
if (isset(
$a->test)) {
   
$b = $a->test;
} else {
   
$b = 5;
}

?>
up
5
Marcin Kuzawiski
8 years ago
A < B and still B < A...

$A = [1 => 1, 2 => 0, 3 => 1];
$B = [1 => 1, 3 => 0, 2 => 1];

var_dump($A < $B);  // TRUE
var_dump($B < $A);  // TRUE

var_dump($A > $B);  // TRUE
var_dump($B > $A);  // TRUE

Next - C and D are comparable, but neither C < D nor D < C (and still C != D)...

$C = [1 => 1, 2 => 1, 3 => 0];
$D = [1 => 1, 3 => 1, 2 => 0];

var_dump($C < $D); // FALSE
var_dump($D < $C); // FALSE

var_dump($C > $D); // FALSE
var_dump($D > $C); // FALSE

var_dump($D == $C); // FALSE
up
4
niall at maranelda dot org
6 years ago
Care must be taken when using the spaceship operator with arrays that do not have the same keys:

- Contrary to the notes above ("Example #2 Transcription of standard array comparison"), it does *not* return null if the left-hand array contains a key that the right-hand array does not.
- Because of this, the result depends on the order you do the comparison in.

For example:

<?php
$a
= ['a' => 1, 'b' => 2, 'c' => 3, 'e' => 4];
$b = ['a' => 1, 'b' => 2, 'd' => 3, 'e' => 4];

var_dump($a <=> $b);        // int(1) : $a > $b because $a has the 'c' key and $b doesn't.

var_dump($b <=> $a);        // int(1) : $b > $a because $b has the 'd' key and $a doesn't.
?>
up
2
Ryan Mott
4 years ago
Searching for "double question mark" operator should find this page (and hopefully after this comment the crawlers will agree)
up
5
Cuong Huy To
12 years ago
In the table "Comparison with Various Types", please move the last line about "Object" to be above the line about "Array", since Object is considered to be greater than Array (tested on 5.3.3)

(Please remove my "Anonymous" post of the same content before. You could check IP to see that I forgot to type my name)
To Top