phparraysarray-difference

Get differences between two arrays and print results as a side-by-side rows grouped by first word


I have:

Array1: ([0] => "Lion 1" [1] => "Cat 1" [2] => "Tiger 1" [3] => "Leopard 1")

Array2: ([0] => "Lion 2" [1] => "Dog 2" [2] => "Tiger 2" [3] => "Leopard 2")

Output to show:

            Array1    |   Array2
            ++++++++++++++++++++
            Lion 1    |   Lion 2
            Cat 1     |   ______ <-Blank row
            Tiger 1   |   Tiger 2
            Leopard 1 |   Leopard 2
Blank row -> _______   |   Dog 2

Solution

  • Here's some code that might be able to help you:

    <pre>
    <?php
    $array1 = Array("Lion 1", "Cat 1", "Tiger 1", "Leopard 1");
    $array2 = Array("Lion 2", "Dog 2", "Tiger 2", "Leopard 2");
    
    function build_map($array) {
        $map = Array();
    
        foreach($array as $val) {
            $parts = explode(' ', $val);
            $map[$parts[0]] = $val;
        }
    
        return $map;
    }
    
    $map1 = build_map($array1);
    $map2 = build_map($array2);
    
    $only1 = array_diff_key($map1, $map2);
    $only2 = array_diff_key($map2, $map1);
    $both = array_intersect_key($map1, $map2);
    
    foreach($both as $key => $val)
        echo $map1[$key]."\t\t".$map2[$key]."\n";
    
    foreach($only1 as $key => $val)
        echo "$val\t\t________\n";
    
    foreach($only2 as $key => $val)
        echo "________\t\t$val\n";
    
    ?>
    </pre>
    

    Its output is the following.

    Lion 1      Lion 2
    Tiger 1     Tiger 2
    Leopard 1       Leopard 2
    Cat 1       ________
    ________        Dog 2
    

    As long as you have one of each animal in each array, this should work.