find the symmetric difference of two maps in php

To find the symmetric difference of two maps in PHP, you can use a combination of array_diff() and array_merge() functions. Here's how you can do it:

main.php
$map1 = array('a' => 'apple', 'b' => 'ball', 'c' => 'cat');
$map2 = array('b' => 'book', 'd' => 'dog', 'c' => 'car');

// Find the keys that are present in only one of the maps
$diffKeys = array_merge(array_diff(array_keys($map1), array_keys($map2)),
                        array_diff(array_keys($map2), array_keys($map1)));

// Find the values corresponding to the diff keys in both maps
$diffVals = array();
foreach ($diffKeys as $key) {
    if (isset($map1[$key])) {
        $diffVals[] = $map1[$key];
    }
    if (isset($map2[$key])) {
        $diffVals[] = $map2[$key];
    }
}

// Combine the keys and values to form the output map
$diffMap = array_combine($diffKeys, $diffVals);
688 chars
21 lines

In the above code, $map1 and $map2 are the two maps whose symmetric difference we want to find. We first find the difference of keys present in both maps using array_diff() and array_merge() functions.

After that, we loop through the diff keys and find the corresponding values in both maps. We add the values to $diffVals array.

Finally, we combine the diff keys and values to form the output map using array_combine() function.

Now, $diffMap contains the symmetric difference of $map1 and $map2 maps.

gistlibby LogSnag