I just read that question about strange php behaviour, and even though I could research a bit more, I'm nowhere near understanding it.
I assume the reader has read the original question and is aware of OP's code block and sample, but in short, OP is trying to compare those two arrays, and while the result is good, the compare function seems to be called erratically:
$chomik = new chomik('a');
$a = array(5, $chomik, $chomik, $chomik);
$b = array($chomik, 'b', 'c', 'd');
array_diff_uassoc($a, $b, 'compare');
The documentation is a bit obscure... but it does state that:
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
As I understand it, that means that the compare()
function should be more like this:
function compare($a, $b) {
echo("$a : $b<br/>");
if($a === $b) return 0;
else if ($a > $b) return 1;
else return -1;
}
however this still gives very strange results, with even more "duplicates"
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
faced with many doubts, I read the compat php function, and the part where the check actually happens is interesting:
foreach ($args[0] as $k => $v) {
for ($i = 1; $i < $array_count; $i++) {
foreach ($args[$i] as $kk => $vv) {
if ($v == $vv) { // compare keys only if value are the same
$compare = call_user_func_array($compare_func, array($k, $kk));
if ($compare == 0) {
continue 3; // value should not be added to the result
}
}
}
}
$result[$k] = $v;
}
here's the actual source (per comment)
The way this code executes the compare function should not be outputting the result we see. Foreach is not able to move back and forth in the keys (AFAIK???), as seems to be the case in the order of the first key here:
1 : 2 3 : 1 2 : 1
moreover, it shouldn't check the keys if the value do not match, so why do all these are checked:
1 : 2 3 : 1 2 : 1 3 : 2 etc...
How can the topmost foreach() in the source code loop back and forth through the keys?!
Why are keys whose values do not match still compared?
Do foreach loops actually continue executing even when they've been continue
d?
Is this an example of concurrency? can call_user_func_array somehow be launched and actually execute the echo("$a : $b<br/>");
of the compare function not in the same order they were "launched"??