Re: Should array_udiff be comparing elements from the same array?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 10.11.2017 at 13:49, Richard Quadling wrote:

> Was testing array_udiff against some complex behaviour. Had an oddity.
> Reduced the code to a simple test ...
> 
> 3v4l.org/XON0v
> 
> <?php
> 
> $array1 = array(1, 2, 3);
> $array2 = array(3, 4, 5);
> 
> print_r(
>     array_udiff(
>         $array1,
>         $array2,
>         function ($a, $b) {
>             static $tests = 0;
>             echo 'array_udiff ', ++$tests, ' ', $a, ' vs ', $b, PHP_EOL;
> 
>             return ($a < $b) ? -1 : (($a > $b) ? 1 : 0);
>         }
>     )
> );
> 
> 
> The output is :
> 
> array_udiff 1 1 vs 2 array_udiff 2 2 vs 3 array_udiff 3 3 vs 4 array_udiff
> 4 4 vs 5 array_udiff 5 1 vs 3 array_udiff 6 1 vs 2 array_udiff 7 2 vs 3
> array_udiff 8 2 vs 3 array_udiff 9 3 vs 3 Array ( [0] => 1 [1] => 2 )
> 
> 
> Tests 1 and 4 suggests that elements from with a single array are being
> compared. Is this expected behaviour?

It is not unexpected, if one considers the obvious implementation of the
function: sort the given arrays first[1], and then do the diff[2].
Sorting the arrays consequently uses the given comparison function, so
this can be applied on elements of the same array and on elements of
different arrays.  Obviously, this requires all arrays to be of the same
shape, at least with regard to the comparison function.  I think the man
page should clarify this.

[1]
<https://github.com/php/php-src/blob/ca1f07b6d733c2f422cb99ffb0e6122b2d5f8b5e/ext/standard/array.c#L5193>
[2]
<https://github.com/php/php-src/blob/ca1f07b6d733c2f422cb99ffb0e6122b2d5f8b5e/ext/standard/array.c#L5235>

-- 
Christoph M. Becker

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php




[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux