I have two arrays which are sorted alphabetically. Each array contains unique values, but some values will be shared between the two arrays.
Sample arrays:
$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 comparison or "diff checker" 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. Okay, I do a foreach
loop for both arrays, but then what?
<ul>
<?php foreach($src as $src_item) : ?>
<li><?php echo $src_item; // what else??? ?></<li>
<?php endforeach; ?>
</ul>
2
Answers
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.
For cases where the input arrays are not guaranteed to be alphabetically ordered and may contain duplicates, I’ve come up with the following script.
Code: (Demo)
To visualize as a table:
My take on @Snor’s approach would be to set up two lookup arrays so that the performance benefits of key sorting and searching can be enjoyed. On relatively large arrays, iterated calls of
in_array()
may place unwanted drag on performance.Code: (Demo)