abhiklpm abhiklpm - 7 months ago 15
PHP Question

Intersection of 2 arrays even if mispelled

$a = array('apple', 'banana', 'orange'); //etc...
$b = array('papel', 'abanan', 'grape'); //etc...


The output should be
'apple', 'banana'
..... You need to use some of the built in array method.

In the second array note that the word 'apple' and 'banana' is spelled wrongly. The words 'papel', 'abanan' can also be like 'leppa', 'nnaab' or any other format, but it must contain all the alphabetic characters of the corresponding word.

Answer

OK, so you say "unique" which implies difference but your example shows intersection. If you need it the other way around use array_udiff() instead:

$result = array_uintersect($a, $b,  function($a, $b) {
                                        $a = str_split($a);
                                        $b = str_split($b);
                                        sort($a);
                                        sort($b);
                                        implode($a);
                                        implode($b);

                                        if($a == $b) {
                                            return 0;
                                        } elseif ($a > $b) {
                                            return 1;
                                        } else {
                                            return -1;
                                        }
                                    });
  • split the strings into arrays
  • sort the arrays
  • implode back into strings
  • compares the strings
  • calling this through array_uintersect() returns elements in $a that are in $b

Yields:

Array
(
    [0] => apple
    [1] => banana
)