downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

array_uintersect_assoc> <array_udiff_uassoc
Last updated: Thu, 17 Sep 2009

view this page in

array_udiff

(PHP 5)

array_udiffИзчислява разлика на масиви посредством функция за обратно извикване за сравнение на данните

Описание

array array_udiff ( array $array1 , array $array2 [, array $ ... ], callback $data_compare_func )

Изчислява разликата на масиви посредством функция за обратно извикване използвана при сравнението. За разлика от нея, функция array_diff() използва вътрешна функция за сравняване на данните.

Параметри

array1

Първият масив.

array2

Вторият масив.

data_compare_func

Функцията за обратно извикване използвана за сравнението.

За сравнението се използва потребителски-дефинирана функция за обратно извикване. Тя трябва да връща цяло число по-малко, равно или по-голямо от нула, ако първият аргумент се счита съответно за по-малък, равен или по-голям от втория.

Връщани стойности

Връща масив, съдържащ всички стойности на array1 , които не са налични в нито един от другите аргументи.

Примери

Example #1 Пример за array_udiff()

<?php
class cr {
    private 
$priv_member;
    function 
cr($val)
    {
        
$this->priv_member $val;
    }

    static function 
comp_func_cr($a$b)
    {
        if (
$a->priv_member === $b->priv_member) return 0;
        return (
$a->priv_member $b->priv_member)? 1:-1;
    }
}
$a = array("0.1" => new cr(9), "0.5" => new cr(12), => new cr(23), 1=> new cr(4), => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), => new cr(3), 1=> new cr(4), => new cr(-15),);

$result array_udiff($a$b, array("cr""comp_func_cr"));
print_r($result);
?>

Примерът по-горе ще изведе:

Array
(
    [0.5] => cr Object
        (
            [priv_member:private] => 12
        )

    [0] => cr Object
        (
            [priv_member:private] => 23
        )

)

Бележки

Забележка: Моля забележете, че функцията проверява само една размерност при n-мерните масиви. Разбира се може да проверите и другите размерности посредством array_udiff($array1[0], $array2[0], "data_compare_func");.

Вж. също

  • array_diff() - Изчислява разлика на масиви
  • array_diff_assoc() - Изчислява разлика на масиви с допълнителна проверка на индекса
  • array_diff_uassoc() - Изчислява разлика на масиви с допълнителна проверка на индекса извършвана от потребителска функция за обратно извикване
  • array_udiff_assoc() - Изчислява разлика на масиви с допълнителна проверка на индекса, сравнявайки данните посредством функция за обратно извикване
  • array_udiff_uassoc() - Изчислява разлика на масиви с допълнителна проверка на индекса, сравнявайки данните и индексите посредством функция за обратно извикване
  • array_intersect() - Изчислява сечението на масиви
  • array_intersect_assoc() - Изчислява сечението на масиви с проверка на индекса
  • array_uintersect() - Изчислява сечението на масиви, сравнявайки данните посредством функция за обратно извикване
  • array_uintersect_assoc() - Изчислява сечението на масиви с допълнителна проверка на индекса, сравнявайки данните посредством функция за обратно извикване
  • array_uintersect_uassoc() - Изчислява сечението на масиви с допълнителна проверка на индекса, сравнявайки данните и индексите посредством функция за обратно извикване



array_uintersect_assoc> <array_udiff_uassoc
Last updated: Thu, 17 Sep 2009
 
add a note add a note User Contributed Notes
array_udiff
jared
07-Jul-2009 07:27
Note that php does the string conversion *before* sending the values to the callback function.
adam dot jorgensen dot za at gmail dot com
08-Oct-2008 01:51
It is not stated, by this function also diffs array1 to itself, removing any duplicate values...
grantwparks at gmail dot com
31-Dec-2007 03:15
Re: "convoluted"

I think the point being made is that array_udiff() can be used not only for comparisons between homogenous arrays, as in your example (and definitely the most common need), but it can be used to compare heterogeneous arrays, too.

Consider:

<?php
function compr_1($a, $b) {
   
$aVal = is_array($a) ? $a['last_name'] : $a;
   
$bVal = is_array($b) ? $b['last_name'] : $b;
    return
strcasecmp($aVal, $bVal);
}

$aEmployees = array(
    array(
'last_name'  => 'Smith',
           
'first_name' => 'Joe',
           
'phone'      => '555-1000'),
    array(
'last_name'  => 'Doe',
           
'first_name' => 'John',
           
'phone'      => '555-2000'),
    array(
'last_name'  => 'Flagg',
           
'first_name' => 'Randall',
           
'phone'      => '666-1000')
    );

$aNames = array('Doe', 'Smith', 'Johnson');
   
$result = array_udiff($aEmployees, $aNames, "compr_1");

print_r($result);
?>

Allowing me to get the "employee" that's not in the name list:

Array ( [2] => Array ( [last_name] => Flagg [first_name] => Randall [phone] => 666-1000 ) )

Something interesting to note, is that the two arguments to the compare function don't correspond to array1 and array2.  That's why there has to be logic in it to handle that either of the arguments might be pointing to the more complex employee array.  (Found this out the hard way.)
Colin
02-Aug-2006 08:15
I think the example given here using classes is convoluting things too much to demonstrate what this function does.

array_udiff() will walk through array_values($a) and array_values($b) and compare each value by using the passed in callback function.

To put it another way, array_udiff() compares $a[0] to $b[0], $b[1], $b[2], and $b[3] using the provided callback function.  If the callback returns zero for any of the comparisons then $a[0] will not be in the returned array from array_udiff().  It then compares $a[1] to $b[0], $b[1], $b[2], and $b[3].  Then, finally, $a[2] to $b[0], $b[1], $b[2], and $b[3].

For example, compare_ids($a[0], $b[0]) === -5 while compare_ids($a[1], $b[1]) === 0.  Therefore, $a[1] is not returned from array_udiff() since it is present in $b.

<?
$a = array(
        array(
                'id' => 10,
                'name' => 'John',
                'color' => 'red',
        ),
        array(
                'id' => 20,
                'name' => 'Elise',
                'color' => 'blue',
        ),
        array(
                'id' => 30,
                'name' => 'Mark',
                'color' => 'red',
        ),
);

$b = array(
        array(
                'id' => 15,
                'name' => 'Nancy',
                'color' => 'black',
        ),
        array(
                'id' => 20,
                'name' => 'Elise',
                'color' => 'blue',
        ),
        array(
                'id' => 30,
                'name' => 'Mark',
                'color' => 'red',
        ),
        array(
                'id' => 40,
                'name' => 'John',
                'color' => 'orange',
        ),
);

function compare_ids($a, $b)
{
    return ($a['id'] - $b['id']);
}
function compare_names($a, $b)
{
    return strcmp($a['name'], $b['name']);
}

$ret = array_udiff($a, $b, 'compare_ids');
var_dump($ret);

$ret = array_udiff($b, $a, 'compare_ids');
var_dump($ret);

$ret = array_udiff($a, $b, 'compare_names');
var_dump($ret);
?>

Which returns the following.

In the first return we see that $b has no entry in it with an id of 10.
<?
array(1) {
  [0]=>
  array(3) {
    ["id"]=>
    int(10)
    ["name"]=>
    string(4) "John"
    ["color"]=>
    string(3) "red"
  }
}
?>

In the second return we see that $a has no entry in it with an id of 15 or 40.
<?
array(2) {
  [0]=>
  array(3) {
    ["id"]=>
    int(15)
    ["name"]=>
    string(5) "Nancy"
    ["color"]=>
    string(5) "black"
  }
  [3]=>
  array(3) {
    ["id"]=>
    int(40)
    ["name"]=>
    string(4) "John"
    ["color"]=>
    string(6) "orange"
  }
}
?>

In third return we see that all names in $a are in $b (even though the entry in $b whose name is 'John' is different, the anonymous function is only comparing names).
<?
array(0) {
}
?>
dmhouse at gmail dot com
20-Jan-2005 09:44
Very easy way of achieving a case-insensitive version of array_diff (or indeed array_diff_assoc, array_intersect or any of these types of functions which have a similar function that takes a callback function as one of their parameters):

array_udiff($array1, $array2, 'strcasecmp');

This works because strcasecmp() compares two strings case-insensitively, as compared to the array_diff() which compares two strings by using the == operator, which is case-sensitive.
aidan at php dot net
28-May-2004 02:11
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat

array_uintersect_assoc> <array_udiff_uassoc
Last updated: Thu, 17 Sep 2009
 
 
show source | credits | sitemap | contact | advertising | mirror sites