PHP

Find Common and Unique Elements Between Two PHP Arrays

Learn how to perform set operations on PHP arrays using array_intersect() to find common elements and array_diff() to identify elements unique to each array.

<?php
$arrayA = ['apple', 'banana', 'cherry', 'date'];
$arrayB = ['banana', 'date', 'elderberry', 'fig'];

// Find common elements (intersection of values)
$commonElements = array_intersect($arrayA, $arrayB);
echo "Common elements: ";
print_r($commonElements); // Result: ['banana', 'date']

// Find elements in A but not in B (difference)
$uniqueToA = array_diff($arrayA, $arrayB);
echo "Elements unique to A: ";
print_r($uniqueToA); // Result: ['apple', 'cherry']

// Find elements in B but not in A (difference)
$uniqueToB = array_diff($arrayB, $arrayA);
echo "Elements unique to B: ";
print_r($uniqueToB); // Result: ['elderberry', 'fig']

// For associative arrays, array_intersect_assoc and array_diff_assoc compare both keys and values
$assocA = ['id' => 1, 'name' => 'Alice', 'role' => 'admin'];
$assocB = ['id' => 1, 'name' => 'Bob', 'status' => 'active'];

$commonAssoc = array_intersect_assoc($assocA, $assocB);
echo "Common associative elements (key & value): ";
print_r($commonAssoc); // Result: ['id' => 1]
?>
How it works: PHP provides powerful functions for comparing arrays as sets. array_intersect() returns an array containing all values that are present in all the input arrays, effectively finding common elements. array_diff() returns an array containing all values from the first array that are not present in any of the other input arrays, identifying unique elements. For associative arrays where both keys and values matter for comparison, array_intersect_assoc() and array_diff_assoc() should be used.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs