Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

Array Operators ใน PHP

บทนำ

PHP กำหนด Operators สำหรับ Array Data Types ดังนี้:

SymbolExampleNameResult
+$a + $bUnionUnion ของ $a และ $b
==$a == $bEqualityTRUE ถ้า Key/Value Pairs เหมือนกัน
===$a === $bIdentityTRUE ถ้า Key/Value Pairs เหมือนกัน ลำดับเดียวกัน Type เดียวกัน
!=$a != $bInequalityTRUE ถ้า $a ไม่เท่ากับ $b
<>$a <> $bInequalityTRUE ถ้า $a ไม่เท่ากับ $b (Alias ของ !=)
!==$a !== $bNon-identityTRUE ถ้า $a ไม่ Identical กับ $b

Union Operator (+)

Append Right-hand Array ไปทางซ้าย ถ้า Key ซ้ำ จะใช้ค่าจาก Left-hand Array (Right-hand ถูก Ignore):

<?php
$arr1 = ["phy" => 70, "che" => 80, "math" => 90];
$arr2 = ["Eng" => 70, "Bio" => 80, "CompSci" => 90];
$arr3 = $arr1 + $arr2;
var_dump($arr3);
?>

ผลลัพธ์

array(6) {
  ["phy"]=> int(70)
  ["che"]=> int(80)
  ["math"]=> int(90)
  ["Eng"]=> int(70)
  ["Bio"]=> int(80)
  ["CompSci"]=> int(90)
}

Comparison Operators

Equality (==)

เท่ากันถ้า Key-Value Pairs เหมือนกัน (Order/Type ไม่สำคัญ):

<?php
$arr1 = [0 => 70, 2 => 80, 1 => 90];
$arr2 = [70, 90, 80];  // Indexed: 0=>70, 1=>90, 2=>80
var_dump($arr1 == $arr2);   // true - same key/value pairs
var_dump($arr2 != $arr1);   // false
?>

ผลลัพธ์

bool(true)
bool(false)

Identity (===)

Identical ก็ต่อเมื่อ Key-Value Pairs เหมือนกัน และ ลำดับเดียวกัน และ Type เดียวกัน:

<?php
$arr1 = [0 => 70, 1 => 80, 2 => 90];
$arr2 = [70, 90, 80];  // 0=>70, 1=>90, 2=>80
var_dump($arr1 === $arr2);  // false - order differs

$arr3 = [70, 80, 90];  // 0=>70, 1=>80, 2=>90
var_dump($arr3 === $arr1);  // true
?>

ผลลัพธ์

bool(false)
bool(true)

ตัวอย่างเพิ่มเติม: Key Type Sensitivity

<?php
$a = ["1" => "one", 2 => "two"];
$b = [1 => "one", "2" => "two"];
var_dump($a == $b);   // true (key "1" == 1, "2" == 2)
var_dump($a === $b);  // false (key types differ: string vs int)
?>

สรุป

  • + = Union (Left-preferred on key collision)
  • == = Same Key/Value Pairs (Loose)
  • === = Same Key/Value Pairs + Order + Types (Strict)
  • != / <> = Not Equal (Loose)
  • !== = Not Identical (Strict)