0

Recently came across function array_uintersect. Just wondering if any one can explain how input params are passed as I got the unexpected inputs passed to callback function, I have already went through This answer but couldn't find answer to my question. Any help or leads will be appreciated, Just trying to understand working of call back function.

NOTE: RESULT OF FUNCTION IS PERFECTLY FINE.

Code:

function myfunction($a,$b) {
    echo "$a -- $b \n";
    if ($a===$b) {
        return 0;
    }
    return ($a>$b)?1:-1;
}

$a1 = array(1,2,3);
$a2 = array(4,5,1);
$result = array_uintersect($a1,$a2,"myfunction");
print_r($result);

As we are passing both the arrays as parameters,expected the inputs to be values from each array where as got below result.

Result:

1 -- 2
2 -- 3
4 -- 5
5 -- 1
4 -- 1
1 -- 1
1 -- 2
2 -- 4
3 -- 4
Array ( [0] => 1 )
1
  • Without looking at the PHP code, I would say there are two sets of results, the first one from where it is sorting $a1 and $a2 (up to 4 -- 1) and the second from where it is comparing them. But that is exactly what was said in the linked question, so what is your question? Commented Mar 6, 2019 at 5:35

1 Answer 1

1

As @Nick mention in his comment (and also the link you shared) claim that array_uintersect sort the arrays before checking for intersect.

This will be the part of:

1 -- 2 // sort first array
2 -- 3 // sort first array
4 -- 5 // sort second array
5 -- 1 // sort second array
4 -- 1 // sort second array

Now both array are: $a1 = [1,2,3] and $a2 = [1,4,5].

Now the intersection part:

1 -- 1  // checking index 0 in both array
1 -- 2  // checking $a2[0] and $a1[1] -> 2 is bigger so let continue with him
2 -- 4  // checking $a1[1] and $a2[1] -> as we already check $a2[0] -> 4 is bigger so continue with him
3 -- 4  // checking $a1[2] and $a2[1] -> 4 is bigger but not $a1[3] so done checking 

Notice the intersection can be done in O(n)because of the sort that done before...

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.