Home > Enterprise >  Compare two arrays in a github-style
Compare two arrays in a github-style

Time:10-15

I have two arrays (sorted alphabetically), with some values matching and some other not, both sides:

$src = ["apple", "cherry", "grape", "lemon", "orange", "strawberry"];
$dst = ["apple", "banana", "cherry", "orange", "pear"];

I'd like to output two lists as they were a file comparson in github style, like this:

1.apple         1.apple
2.              2.banana
3.cherry        3.cherry
4.grape         4.
5.lemon         5.
6.orange        6.orange
7.              7.pear
8.strawberry    8.

I'm stuck in finding the right way to do this: ok, I do a foreach loop for both arrays and...then?

<ul>
<?php foreach($src as $src_item) : ?>
    <li><?php echo $src_item; // what else??? ?></<li>
<?php endforeach; ?>
</ul>

Please any help? Thanks in advance

CodePudding user response:

You could simply combine the arrays unique items (then re-sort it!) Then you can just loop the new array and check which items are in the original 2 arrays.

<?php

$src = ["apple", "cherry", "grape", "lemon", "orange", "strawberry"];
$dst = ["apple", "banana", "cherry", "orange", "pear"];

$combined_items = array_unique(array_merge($src, $dst));
sort($combined_items);

$new_array = [];

foreach($combined_items as $item){
    $item1 = in_array($item, $src) ? $item : null;
    $item2 = in_array($item, $dst) ? $item : null;
    $new_array[] = [$item1, $item2];
}

// $new_array will contain ["apple","apple"], [null, "banana"], etc.
  • Related