PHP

Finding Differences and Intersections Between PHP Arrays

Learn to efficiently compare two or more PHP arrays to find elements unique to one or common among them using `array_diff` and `array_intersect` functions.

<?php
$array1 = ['apple', 'banana', 'orange', 'grape'];
$array2 = ['banana', 'kiwi', 'apple', 'mango'];
$array3 = ['apple', 'banana', 'strawberry'];

// Find values in $array1 that are not in $array2
$diff1_2 = array_diff($array1, $array2);
echo "Elements in array1 but not in array2: " . implode(', ', $diff1_2) . "
";
// Expected: orange, grape

// Find values in $array2 that are not in $array1
$diff2_1 = array_diff($array2, $array1);
echo "Elements in array2 but not in array1: " . implode(', ', $diff2_1) . "
";
// Expected: kiwi, mango

// Find common values in $array1 and $array2
$intersect1_2 = array_intersect($array1, $array2);
echo "Common elements in array1 and array2: " . implode(', ', $intersect1_2) . "
";
// Expected: apple, banana

// Find common values in all three arrays
$intersect_all = array_intersect($array1, $array2, $array3);
echo "Common elements in all three arrays: " . implode(', ', $intersect_all) . "
";
// Expected: apple, banana

// For associative arrays, use array_diff_assoc, array_intersect_assoc to compare by key and value
$assoc1 = ['a' => 'apple', 'b' => 'banana', 'c' => 'orange'];
$assoc2 = ['b' => 'banana', 'd' => 'kiwi', 'a' => 'apple'];

$assoc_diff = array_diff_assoc($assoc1, $assoc2);
echo "Associative differences in assoc1 vs assoc2: " . json_encode($assoc_diff) . "
";
// Expected: {"c":"orange"}

$assoc_intersect = array_intersect_assoc($assoc1, $assoc2);
echo "Associative intersection of assoc1 and assoc2: " . json_encode($assoc_intersect) . "
";
// Expected: {"a":"apple","b":"banana"}
?>
How it works: This snippet demonstrates `array_diff()` and `array_intersect()` for comparing elements between arrays. `array_diff()` returns values from the first array that are not present in any other input arrays. Conversely, `array_intersect()` returns all values that are present in all input arrays. For associative arrays, `array_diff_assoc()` and `array_intersect_assoc()` compare elements based on both their keys and values.

Need help integrating this into your project?

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

Hire DigitalCodeLabs