CakeFest 2024: The Official CakePHP Conference

array_udiff

(PHP 5, PHP 7, PHP 8)

array_udiffComputa a diferença de arrays usando uma função de callback para comparação dos dados

Descrição

array_udiff(array $array, array ...$arrays, callable $value_compare_func): array

Computa a diferença de arrays usando uma função de callback para comparação dos dados. Esta é contrária a array_diff() que usa uma função interna para comparar os dados.

Parâmetros

array

O primeiro array.

arrays

Arrays para comparar.

value_compare_func

A função de comparação deve retornar um inteiro menor que, igual ou maior que zero se o primeiro argumento for considerado respectivamente menor que, igual ou maior que o segundo.

callback(mixed $a, mixed $b): int
Cuidado

Retornar valores não inteiros da função de comparação, como float, resultará em uma conversão interna do valor retornado da função callback para int. Portanto, valores como 0.99 e 0.1 serão convertidos para o valor inteiro 0, o que comparará esses valores como iguais.

Cuidado

A função chamada de ordenação deve lidar com qualquer valor de qualquer array em qualquer ordem, independentemente da ordem em que eles foram originalmente fornecidos. O motivo é que cada array individual é primeiramente ordenado antes de ser comparado com outros arrays. Por exemplo:

<?php
$arrayA
= ["string", 1];
$arrayB = [["value" => 1]];
// $item1 e $item2 podem ser "string", 1 ou ["value" => 1]
$compareFunc = static function ($item1, $item2) {
$value1 = is_string($item1) ? strlen($item1) : (is_array($item1) ? $item1["value"] : $item1);
$value2 = is_string($item2) ? strlen($item2) : (is_array($item2) ? $item2["value"] : $item2);
return
$value1 <=> $value2;
};
?>

Valor Retornado

Retorna um array contendo todos os valores de array que não estão presentes em qualquer dos outros argumentos.

Exemplos

Exemplo #1 Exemplo de array_udiff() usando Objetos stdClass

<?php
// Arrays para comprar
$array1 = array(new stdClass, new stdClass,
new
stdClass, new stdClass,
);

$array2 = array(
new
stdClass, new stdClass,
);

// Define algumas propriedades para cada objeto
$array1[0]->largura = 11; $array1[0]->altura = 3;
$array1[1]->largura = 7; $array1[1]->altura = 1;
$array1[2]->largura = 2; $array1[2]->altura = 9;
$array1[3]->largura = 5; $array1[3]->altura = 7;

$array2[0]->largura = 7; $array2[0]->altura = 5;
$array2[1]->largura = 9; $array2[1]->altura = 2;

function
comparar_por_area($a, $b) {
$areaA = $a->largura * $a->altura;
$areaB = $b->largura * $b->altura;

if (
$areaA < $areaB) {
return -
1;
} elseif (
$areaA > $areaB) {
return
1;
} else {
return
0;
}
}

print_r(array_udiff($array1, $array2, 'comparar_por_area'));
?>

O exemplo acima produzirá:

Array
(
    [0] => stdClass Object
        (
            [largura] => 11
            [altura] => 3
        )

    [1] => stdClass Object
        (
            [largura] => 7
            [altura] => 1
        )

)

Exemplo #2 Exemplo de array_udiff() usando Objetos DateTime

<?php
class MeuCalendario {
public
$livres = array();
public
$reservadas = array();

public function
__construct($semana = 'now') {
$inicio = new DateTime($semana);
$inicio->modify('Monday this week midnight');
$fim = clone $inicio;
$fim->modify('Friday this week midnight');
$intervalo = new DateInterval('P1D');
foreach (new
DatePeriod($inicio, $intervalo, $fim) as $tempoLivre) {
$this->livres[] = $tempoLivre;
}
}

public function
marcarCompromisso(DateTime $data, $nota) {
$this->reservadas[] = array('data' => $data->modify('midnight'), 'nota' => $nota);
}

public function
checarDisponibilidade() {
return
array_udiff($this->livres, $this->reservadas, array($this, 'compararPersonalizado'));
}

public function
compararPersonalizado($livres, $reservadas) {
if (
is_array($livres)) $a = $livres['data'];
else
$a = $livres;
if (
is_array($reservadas)) $b = $reservadas['data'];
else
$b = $reservadas;
if (
$a == $b) {
return
0;
} elseif (
$a > $b) {
return
1;
} else {
return -
1;
}
}
}

// Cria um calendário para compromissos semanais
$meuCalendario = new MeuCalendario;

// Marca alguns compromissos para esta semana
$meuCalendario->marcarCompromisso(new DateTime('Monday this week'), "Limpando apartamento do GoogleGuy.");
$meuCalendario->marcarCompromisso(new DateTime('Wednesday this week'), "Fazendo uma viagem de snowboarding.");
$meuCalendario->marcarCompromisso(new DateTime('Friday this week'), "Corrigindo código bugado.");

// Checar disponibilidade de dias comparando datas $reservadas com datas $livres
echo "Estou disponível nos seguintes dias desta semana...\n\n";
foreach (
$meuCalendario->checarDisponibilidade() as $livre) {
echo
$livre->format('l'), "\n";
}
echo
"\n\n";
echo
"Estou ocupado(a) nos seguintes dias desta semana...\n\n";
foreach (
$meuCalendario->reservadas as $reservada) {
echo
$reservada['data']->format('l'), ": ", $reservada['nota'], "\n";
}
?>

O exemplo acima produzirá:

Estou disponível nos seguintes dias desta semana...

Tuesday
Thursday


Estou ocupado(a) nos seguintes dias desta semana...

Monday: Limpando apartamento do GoogleGuy.
Wednesday: Fazendo uma viagem de snowboarding.
Friday: Corrigindo código bugado.

Notas

Nota: Por favor note que esta função somente checa uma dimensão de um array n-dimensional. É claro que você pode checar dimensões mais profundas usando array_udiff($array1[0], $array2[0], "data_compare_func");.

Veja Também

  • array_diff() - Computa as diferenças entre arrays
  • array_diff_assoc() - Computa a diferença entre arrays com checagem adicional de índice
  • array_diff_uassoc() - Computa a diferença entre arrays com checagem adicional de índice que feita por uma função de callback fornecida pelo usuário
  • array_udiff_assoc() - Computa a diferença entre arrays com checagem adicional de índice, compara dados por uma função de callback
  • array_udiff_uassoc() - Computa a diferença entre arrays com checagem adicional de índice, compara dados e índices por uma função de callback
  • array_intersect() - Calcula a interseção entre arrays
  • array_intersect_assoc() - Computa a interseção de arrays com uma adicional verificação de índice
  • array_uintersect() - Computa a interseção de array, comparando dados com uma função callback
  • array_uintersect_assoc() - Computa a interseção de arrays com checagem adicional de índice, compara os dados utilizando uma função de callback
  • array_uintersect_uassoc() - Computa a interseção de arrays com checagem adicional de índice, compara os dados e os índices utilizando funções de callback separadas

add a note

User Contributed Notes 9 notes

up
52
Colin
17 years ago
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) {
}
?>
up
32
napcoder
7 years ago
Note that the compare function is used also internally, to order the arrays and choose which element compare against in the next round.

If your compare function is not really comparing (ie. returns 0 if elements are equals, 1 otherwise), you will receive an unexpected result.
up
7
grantwparks at gmail dot com
16 years ago
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.)
up
17
adam dot jorgensen dot za at gmail dot com
15 years ago
It is not stated, by this function also diffs array1 to itself, removing any duplicate values...
up
15
b4301775 at klzlk dot com
12 years ago
Quick example for using array_udiff to do a multi-dimensional diff

Returns values of $arr1 that are not in $arr2

<?php
$arr1
= array( array('Bob', 42), array('Phil', 37), array('Frank', 39) );

$arr2 = array( array('Phil', 37), array('Mark', 45) );

$arr3 = array_udiff($arr1, $arr2, create_function(
'$a,$b',
'return strcmp( implode("", $a), implode("", $b) ); ')
);

print_r($arr3);
?>

Output:

Array
(
[0] => Array
(
[0] => Bob
[1] => 42
)

[2] => Array
(
[0] => Frank
[1] => 39
)

)
1

Hope this helps someone
up
3
Jorge Morales (morales2k)
5 years ago
I find it that this is an ideal place to apply the spaceship operator, but it was not used in the examples.

Here is Example#1 using the spaceship operator in the comparison function.

<?php
// Arrays to compare
$array1 = array(new stdclass, new stdclass,
new
stdclass, new stdclass,
);

$array2 = array(
new
stdclass, new stdclass,
);

// Set some properties for each object
$array1[0]->width = 11; $array1[0]->height = 3;
$array1[1]->width = 7; $array1[1]->height = 1;
$array1[2]->width = 2; $array1[2]->height = 9;
$array1[3]->width = 5; $array1[3]->height = 7;

$array2[0]->width = 7; $array2[0]->height = 5;
$array2[1]->width = 9; $array2[1]->height = 2;

function
compare_by_area($a, $b) {
$areaA = $a->width * $a->height;
$areaB = $b->width * $b->height;

return
$areaA <=> $areaB;
}

print_r(array_udiff($array1, $array2, 'compare_by_area'));
?>

The output is:
Array
(
[0] => stdClass Object
(
[width] => 11
[height] => 3
)

[1] => stdClass Object
(
[width] => 7
[height] => 1
)

)

I find it is pretty awesome you can substitute all of these lines:
if ($areaA < $areaB) {
return -1;
} elseif ($areaA > $areaB) {
return 1;
} else {
return 0;
}

with just:

return $areaA <=> $areaB;

Neat!
up
2
dmhouse at gmail dot com
19 years ago
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.
up
-2
jared
14 years ago
Note that php does the string conversion *before* sending the values to the callback function.
up
-3
aidan at php dot net
19 years ago
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
To Top