array_diff

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

array_diffComputa as diferenças entre arrays

Descrição

function array_diff(array $array, array ...$arrays): array

Compara array com um ou mais arrays e retorna os valores no array que não estão presentes em nenhum dos outros arrays.

Parâmetros

array

O array a ser comparado

arrays

Arrays para comparar

Valor Retornado

Retorna um array contendo todas as entradas de array que não estão presentes em nenhum dos outros arrays. Chaves no array array são preservadas.

Registro de Alterações

Versão Descrição
8.0.0 Esta função agora pode ser chamada com apenas um parâmetro. Anteriormente, pelo menos dois parâmetros eram necessários.

Examples

Exemplo #1 Exemplo da função array_diff()

<?php
$array1 = array("a" => "verde", "vermelho", "azul", "vermelho");
$array2 = array("b" => "verde", "amarelo", "vermelho");
$result = array_diff($array1, $array2);

print_r($result);
?>

Multiplas ocorrências de $array1 são todas tratadas da mesma maneira. Isto irá mostrar:

Array
(
  [1] => azul
)

Dois elementos são considerados iguais se e somente se (string) $elem1 === (string) $elem2. Isto é, quando a representação em string é a mesma.

Exemplo #2 Exemplo de array_diff() com tipos não correspondentes

<?php
// Isto irá gerar uma Notícia de que um array não pode ser convertido em uma string.
$fonte = [1, 2, 3, 4];
$filtro = [3, 4, [5], 6];
$resultado = array_diff($fonte, $filtro);

// Enquanto isto não é um problema, uma vez que o objeto pode ser convertido em string.
class S {
  private $v;

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

  public function __toString() {
    return $this->v;
  }
}

$fonte = [new S('a'), new S('b'), new S('c')];
$filtro = [new S('b'), new S('c'), new S('d')];

$resultado = array_diff($fonte, $filtro);

// $resultado agora contém uma instância de S('a');
var_dump($resultado);
?>

Para usar uma função de comparação alternativa, veja array_udiff().

Notas

Nota:

Esta função verifica somente uma dimensão de um array n-dimensional. É claro que as dimensões mais profundas podem ser verificadas usando array_diff($array1[0], $array2[0]);.

Veja também

  • array_diff_assoc() - Computa a diferença entre arrays com checagem adicional de índice
  • array_udiff() - Computa a diferença de arrays usando uma função de callback para comparação dos dados
  • array_intersect() - Calcula a interseção entre arrays
  • array_intersect_assoc() - Computa a interseção de arrays com uma adicional verificação de índice

adicionar nota

Notas de Usuários 29 notes

up
264
nilsandre at gmx dot de
19 years ago
Again, the function's description is misleading right now. I sought a function, which (mathematically) computes A - B, or, written differently, A \ B. Or, again in other words, suppose 

A := {a1, ..., an} and B:= {a1, b1, ... , bm}

=> array_diff(A,B) = {a2, ..., an}

array_diff(A,B) returns all elements from A, which are not elements of B (= A without B).

You should include this in the documentation more precisely, I think.
up
74
Anonymous
20 years ago
array_diff provides a handy way of deleting array elements by their value, without having to unset it by key, through a lengthy foreach loop and then having to rekey the array.

<?php

//pass value you wish to delete and the array to delete from
function array_delete( $value, $array)
{
    $array = array_diff( $array, array($value) );
    return $array;
}
?>
up
9
xmgr2 at protonmail dot com
1 year ago
The description is kinda ambiguous at first glance, one might think that the array_diff function returns the differences across *all* given arrays (which is what I was actually looking for, and that's why I was surprised that, in the example code, the result did not include "yellow").

However, i wrote a neat oneliner to compute the differences across all given arrays:

<?php
# Returns an array with values that are unique across all of the given arrays
function array_unique_values(...$arrays) {
    return array_keys(array_filter(array_count_values(array_merge(...$arrays)), fn($count) => $count === 1));
}

# Example:
$array1 = ['a', 'b', 'c', 'd'];
$array2 = ['a', 'b', 'x', 'y'];
$array3 = ['a', '1', 'y', 'z'];

print_r(array_unique_values($array1, $array2, $array3));
?>

Result:
Array
(
    [0] => c
    [1] => d
    [2] => x
    [3] => 1
    [4] => z
)
up
40
james dot PLZNOSPAM at bush dot cc
9 years ago
If you want a simple way to show values that are in either array, but not both, you can use this:

<?php
function arrayDiff($A, $B) {
    $intersect = array_intersect($A, $B);
    return array_merge(array_diff($A, $intersect), array_diff($B, $intersect));
}
?>

If you want to account for keys, use array_diff_assoc() instead; and if you want to remove empty values, use array_filter().
up
10
Al Amin Chayan (mail at chayan dot me)
5 years ago
<?php
/**
   * Check If An Array Is A Subset Of Another Array
   *
   * @param  array $subset
   * @param  array $set
   * @return bool
   */
function is_subset(array $subset, array $set): bool {
     return (bool)!array_diff($subset, $set);
}

$u = [1, 5, 6, 8, 10];
$a = [1, 5];
$b = [6, 7];

var_dump(is_subset($a, $u)); // true
var_dump(is_subset($b, $u)); // false
up
25
firegun at terra dot com dot br
17 years ago
Hello guys,

I´ve been looking for a array_diff that works with recursive arrays, I´ve tried the ottodenn at gmail dot com function but to my case it doesn´t worked as expected, so I made my own. I´ve haven´t tested this extensively, but I´ll explain my scenario, and this works great at that case :D

We got 2 arrays like these:

<?php
$aArray1['marcie'] = array('banana' => 1, 'orange' => 1, 'pasta' => 1);
$aArray1['kenji'] = array('apple' => 1, 'pie' => 1, 'pasta' => 1);

$aArray2['marcie'] = array('banana' => 1, 'orange' => 1);
?>

As array_diff, this function returns all the items that is in aArray1 and IS NOT at aArray2, so the result we should expect is:

<?php
$aDiff['marcie'] = array('pasta'