May 2, 2012

array_diff_uassoc () in PHP?

Question by Rajiv

function myfunction($v1, $v2) {
    if ($v1 == $v2) {
        return 0;
    }
    if ($v1 > $v2) {
        return 1;
    } else {
        return-1;
    }
}

$a1 = array(5 => "Rat", 2 => "Cat", 7 => "Horse");
$a2 = array(8 => "Rat",4 => "Cat",7 => "Horse");
print_r(array_diff_uassoc($a1, $a2, "myfunction"));

How it is executed?

Answer by Starx

Please read the manual.

It basically compares two or more arrays, checking for differences, before comparing the keys in a user-defined function, then returns an array with the keys and values from the first array, if the function allows it.

Unlike array_diff_assoc() an user supplied callback function is used for the indices comparison, not internal function.

Please see the live version of your code here. It calculates the difference based on the function and gives the following output.

Array
(
    [5] => Rat
    [2] => Cat
)

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!