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.

1

1 Answer 1

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');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.