Web Analytics

PHP Array Operators

Beginner~20 min read

PHP provides special operators for working with arrays. These operators let you combine arrays and compare them in different ways. Understanding the difference between union and merge is crucial!

Array Operators Overview

Operator Name Description
+ Union Combines arrays (keeps first values for duplicate keys)
== Equality True if same key-value pairs (any order)
=== Identity True if same key-value pairs, same order, same types
!= Inequality True if not equal
<> Inequality True if not equal (alternative)
!== Non-identity True if not identical
Output
Click Run to execute your code

Array Union (+)

Combines arrays, keeping the FIRST value for duplicate keys:

<?php
$arr1 = ["a" => "apple", "b" => "banana"];
$arr2 = ["b" => "blueberry", "c" => "cherry"];

$result = $arr1 + $arr2;
print_r($result);
// ["a" => "apple", "b" => "banana", "c" => "cherry"]
// Note: "banana" kept, not "blueberry"
?>
Union vs array_merge():
  • Union (+): Keeps first value for duplicate keys
  • array_merge(): Overwrites with last value

Array Equality (==)

Checks if arrays have same key-value pairs (order doesn't matter):

<?php
$a = ["x" => 1, "y" => 2];
$b = ["y" => 2, "x" => 1];  // Different order

var_dump($a == $b);  // true (same pairs, order ignored)
?>

Array Identity (===)

Checks if arrays have same key-value pairs in same order with same types:

<?php
$a = ["x" => 1, "y" => 2];
$b = ["y" => 2, "x" => 1];  // Different order

var_dump($a === $b);  // false (different order)

$c = ["x" => 1, "y" => 2];
var_dump($a === $c);  // true (same order, same types)
?>

Summary

  • +: Union (keeps first values for duplicate keys)
  • ==: Equality (same pairs, any order)
  • ===: Identity (same pairs, same order, same types)
  • !=, <>: Not equal
  • !==: Not identical
  • Union โ‰  Merge: Different behavior for duplicates

What's Next?

Congratulations! You've completed Module 3 and mastered all PHP operators. In the next module, we'll dive into Control Flow - using if statements, loops, and switch statements to control program execution!