0

I have two multidimensional arrays, each element in the array consists of 2 elements, the first is a string and the second is an integer. I want to get the difference between the two multidimensional arrays based on the second value if and only if the first elements are equal. I am using array_udiff such as below:

$arrdiff = array_udiff($arr1, $arr2, 'udiffCompare');

I implemented the function array_udiff such that if the first element is different to return them as equal since I don't want it to appear in the difference, and if the first element is equal then compare the second element and return accordingly, below is the function I implemented

function udiffCompare($a, $b) {
    return strcmp($a[0], $b[0]) == 0 ? $ a[1] - $b[1] : 0;
}

However, even though I have two arrays with the same first element but a different second element, they are not returned in the result of array_udiff function.

Am I missing anything here? Any help is appreciated.

t j
  • 7,026
  • 12
  • 46
  • 66
Khaled
  • 3
  • 2
  • 1
    Explanation for the unexpected behaviour - https://stackoverflow.com/questions/18092562/misunderstanding-the-behavior-of-array-udiff – Udayraj Deshmukh Feb 13 '18 at 00:13

1 Answers1

1

The problem is, you're looking for a difference within an intersection, using only a difference function.

Try computing the intersection based on the string value, and using the result to compute the difference based on the int value.

function sameString ($a, $b) {
    return strcmp($a[0], $b[0]);
}

function differentInt($a, $b) {
    return $a[1] - $b[1];
}

$diff = array_udiff(array_uintersect($arr1, $arr2, 'sameString'), $arr2, 'differentInt');
Don't Panic
  • 41,125
  • 10
  • 61
  • 80