Array_diff_uassoc behavior is not clear

First of all, I have to mention that I dug into manual and php documents and did not find the answer. Here is the code I'm using:

class chomik {

    public $state = 'normal';
    public $name = 'no name';

    public function __construct($name) {
        $this->name = $name;
    }

    public function __toString() {
        return $this->name . " - " . $this->state;
    }
}

function compare($a, $b) {
    echo("$a : $b<br/>");
    if($a != $b) {
        return 0;
    }
    else return 1;
}

$chomik = new chomik('a');
$a = array(5, $chomik, $chomik, $chomik);
$b = array($chomik, 'b', 'c', 'd');
array_diff_uassoc($a, $b, 'compare');

What I thought, array_diff_uassoc will compare all the values ​​of these two arrays, and if the values ​​exist, then the keys will be compared. And the output of this code:

1 : 0
3 : 1
2 : 1
3 : 2
1 : 0
3 : 1
2 : 1
3 : 2
3 : 3
3 : 2
2 : 3
1 : 3
0 : 3

So, first of all, why are some pairs (1: 0 or 3: 1) duplicated? Does this mean that the function has forgotten that it has already compared these items? I thought that it would compare all pairs with equal value, but I do not see it in the output. Did I miss something?

So the question is: what is the exact behavior of this function in terms of the order of comparison, and why do I see this duplication? (my php version if that helps: php version 5.3.6-13ubuntu3.6)

...

+5
3

op comment,

, ($ a [0])

array_diff($a, $b);?

array(1) {
  [0]=>
  int(5)
}

,

, :

, , , , .

, , compare() :

function compare($a, $b) {
    echo("$a : $b<br/>");
    if($a === $b) return 0;
    else if ($a > $b) return 1;
    else return -1;
}

:

1 : 0
1 : 2
3 : 1
2 : 1
3 : 2
1 : 0
1 : 2
3 : 1
2 : 1
3 : 2
0 : 0
1 : 0
1 : 1
2 : 0
2 : 1
2 : 2
3 : 0
3 : 1
3 : 2
3 : 3

, .

0

, .

, 1, .

.

, . , .

,

$one = array(a,b,c,'hot'=>d); // d has no match and  will be returned as array and go to the function alone
$two = array(a,b,c,d,e,f); //

$one hot = > d $two 0 = > d $one hot = > d .

- PHP , ===.

, . "0" = > d 0 = > d , .

, PHP7, .

, , php . :

, if ($ a!= $b) { . , ! ==. , . , , array_udiff,

0

. PHP github ( ++, , , ), . (https://github.com/php/php-src/blob/master/ext/standard/array.c)

, ​​ 4308

PHP_FUNCTION(array_diff_uassoc)
{
    php_array_diff(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIFF_ASSOC, DIFF_COMP_DATA_INTERNAL, DIFF_COMP_KEY_USER);
}

, , php_array_diff, 3938. , , 265 , , .

. C , , , . , , , , , , . , , , , .

, , , echo compare ? array_diff_uassoc . , . C-, . , .

Perhaps you could use this replacement function written in php: http://pear.php.net/reference/PHP_Compat-1.6.0a2/__filesource/fsource_PHP_Compat__PHP_Compat-1.6.0a2CompatFunctionarray_diff_uassoc.php.html

That way, you can rely on behavior that won't change, and you have complete control over your inner workings ...

0
source

All Articles