phparraysfilterarray-difference

Get bilateral differences between two flat arrays


So here is my code from my genetics calculator:

// Set up male dominant traits
$maleDom = 'WT';
// Set up male recessive traits
$maleRec = 'ba,b,ec';
// Set up male snow traits
$maleSnow = '';

// Set up female dominant traits
$femaleDom = 'WT';
// Set up female recessive traits
$femaleRec = 'ba,b,mp';
// Set up female snow traits
$femaleSnow = '';

$maleRecArray = explode(',', $maleRec);
$femaleRecArray = explode(',', $femaleRec);

$nonMatchedRecessives = array_diff($maleRecArray, $femaleRecArray);

Which throws out Array ( [2] => ec ). But you can see that ec and mp exist in separate arrays. So surely it should be showing mp too as it's different to the other array?


Solution

  • You need to run it twice, comparing the 2 arrays in reverse order, like this:

    array_merge(array_diff($maleRecArray, $femaleRecArray), array_diff($femaleRecArray, $maleRecArray));
    

    Which spits out:

    Array
    (
        [0] => ec
        [1] => mp
    )
    

    Example