PHP
Find Differences and Common Elements Between Arrays
Discover how to efficiently compare two or more PHP arrays to find unique elements or common elements using functions like `array_diff` and `array_intersect`.
<?php
$arrayA = ['apple', 'banana', 'orange', 'grape'];
$arrayB = ['banana', 'grape', 'kiwi'];
$arrayC = ['apple', 'strawberry'];
// Find values in arrayA that are not in arrayB
$diffAB = array_diff($arrayA, $arrayB);
print_r($diffAB);
/* Output:
Array
(
[0] => apple
[2] => orange
)
*/
// Find common values in arrayA and arrayB
$intersectAB = array_intersect($arrayA, $arrayB);
print_r($intersectAB);
/* Output:
Array
(
[1] => banana
[3] => grape
)
*/
// Find common values across arrayA, arrayB, and arrayC
$intersectAll = array_intersect($arrayA, $arrayB, $arrayC);
print_r($intersectAll);
/* Output:
Array
(
)
(No common values among all three)
*/
// Using array_diff_assoc for comparing both keys and values
$assocA = ['a' => 1, 'b' => 2, 'c' => 3];
$assocB = ['b' => 2, 'd' => 4, 'c' => '3']; // 'c' value differs
$diffAssoc = array_diff_assoc($assocA, $assocB);
print_r($diffAssoc);
/* Output:
Array
(
[a] => 1
[c] => 3
)
*/
How it works: PHP provides powerful functions for comparing arrays. `array_diff()` returns an array containing all values from the first array that are not present in any other arrays. `array_intersect()` returns an array containing all values that are present in all arrays. For associative arrays, `array_diff_assoc()` and `array_intersect_assoc()` compare both keys and values, offering more granular control when identifying differences or commonalities based on the entire key-value pair.