abhiklpm abhiklpm - 2 years ago 74
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 Source

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);

                                        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


    [0] => apple
    [1] => banana
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download