배열 연산자
배열 연산자
PHP의 배열 연산자는 합집합(union), 동등(equal), 일치(identical) 비교 등을 처리해요. 특히 + 연산자는 배열을 이어 붙일 때 써요.
출처: Array Operators
본문
배열 연산자를 표로 정리하면 이렇게 돼요.
| 예시 | 이름 | 결과 |
|---|---|---|
$a + $b |
Union | $a와 $b의 합집합 |
$a == $b |
Equality | $a와 $b가 같은 키/값 쌍을 가질 때 true |
$a === $b |
Identity | $a와 $b가 같은 키/값 쌍을 같은 순서로, 같은 타입으로 가질 때 true |
$a != $b |
Inequality | $a가 $b와 같지 않을 때 true |
$a <> $b |
Inequality | $a가 $b와 같지 않을 때 true |
$a !== $b |
Non-identity | $a가 $b와 일치하지 않을 때 true |
+ 연산자는 오른쪽 배열을 왼쪽 배열 뒤에 이어 붙인 결과를 돌려줘요. 이때 두 배열에 모두 존재하는 키가 있다면 왼쪽 배열의 요소가 사용되고, 오른쪽 배열의 같은 키 요소는 무시돼요.
Example #1 배열 추가(Append) 연산자
<?php
$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");
$c = $a + $b; // Union of $a and $b
echo "Union of \$a and \$b: \n";
var_dump($c);
$c = $b + $a; // Union of $b and $a
echo "Union of \$b and \$a: \n";
var_dump($c);
$a += $b; // Union of $a += $b is $a and $b
echo "Union of \$a += \$b: \n";
var_dump($a);
?>
위 예제의 출력은 다음과 같아요.
Union of $a and $b:
array(3) {
["a"]=>
string(5) "apple"
["b"]=>
string(6) "banana"
["c"]=>
string(6) "cherry"
}
Union of $b and $a:
array(3) {
["a"]=>
string(4) "pear"
["b"]=>
string(10) "strawberry"
["c"]=>
string(6) "cherry"
}
Union of $a += $b:
array(3) {
["a"]=>
string(5) "apple"
["b"]=>
string(6) "banana"
["c"]=>
string(6) "cherry"
}
배열의 요소는 키와 값이 같으면 비교했을 때 동등한 것으로 간주돼요.
Example #2 배열 비교하기
<?php
$a = array("apple", "banana");
$b = array(1 => "banana", "0" => "apple");
var_dump($a == $b); // bool(true)
var_dump($a === $b); // bool(false)
?>
더 알아보기
- array 타입(Array type)
- 배열 함수(Array functions)