PHP

Calculate Symmetric Difference of Two Arrays

Find elements that are unique to either of two PHP arrays, effectively computing their symmetric difference (elements not common to both).

function array_symmetric_difference(array $array1, array $array2): array {
    // Elements in array1 but not in array2
    $diff1 = array_diff($array1, $array2);
    
    // Elements in array2 but not in array1
    $diff2 = array_diff($array2, $array1);
    
    // Combine the unique elements from both differences
    return array_merge($diff1, $diff2);
}

$setA = [1, 2, 3, 4, 5];
$setB = [4, 5, 6, 7, 8];

$symmetricDifference = array_symmetric_difference($setA, $setB);
print_r($symmetricDifference);
// Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 6 [4] => 7 [5] => 8 )
How it works: This snippet demonstrates how to calculate the symmetric difference between two arrays, which means finding all elements that are present in either array but not in both. It accomplishes this by first using `array_diff` to find elements unique to the first array (`$array1 - $array2`), then using `array_diff` again to find elements unique to the second array (`$array2 - $array1`). Finally, `array_merge` is used to combine these two sets of unique elements into a single array, representing the complete symmetric difference.

Need help integrating this into your project?

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

Hire DigitalCodeLabs