array_diff

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

array_diffDizilerin farkını hesaplar

Açıklama

function array_diff(array $dizi, array ...$diziler): array

dizi ile bir veya daha fazla diziyi karşılaştırır ve diğer dizilerde bulunmayan değerleri dizi içinde döndürür.

Bağımsız Değişkenler

dizi

Karşılaştırılacak dizi.

diziler

Karşılaştırılacak diğer diziler.

Dönen Değerler

Diğer dizilerde mevcut olmayan dizi girdilerinden oluşan bir dizi ile döner. dizi içindeki anahtarlar korunur.

Sürüm Bilgisi

Sürüm: Açıklama
8.0.0 Bu işlev artık yalnızca tek bir bağımsız değişken ile çağrılabiliyor. Evvelve en az iki bağımsız değişken gerekirdi.

Örnekler

Örnek 1 - array_diff() örneği

<?php
$dizi1 = array("a" => "green", "red", "blue", "red");
$dizi2 = array("b" => "green", "yellow", "red");
$result = array_diff($dizi1, $dizi2);

print_r($result);
?>

$dizi1 içinde aynı değerde birden fazla eleman varsa hepsi tek bir girdi kabul edilir ve çıktı şöyle olur:

Array
(
    [1] => blue
)

İki elemanın eşit olması için sadece ve sadece (string) $elem1 === (string) $elem2 olmalıdır. Başka bir deyişle, dize gösterimleri aynı olmalıdır.

Örnek 2 - Eşleşmeyen türler ile array_diff()

<?php
// dizi dizeye dönüşürülemezse bir uyarı üretilir.
$source = [1, 2, 3, 4];
$filter = [3, 4, [5], 6];
$result = array_diff($source, $filter);

// nesneler dizeye dönüştürülebildiğinden burada sorun çıkmaz.
class S {
  private $v;

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

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

$source = [new S('a'), new S('b'), new S('c')];
$filter = [new S('b'), new S('c'), new S('d')];

$result = array_diff($source, $filter);

// $result tek bir S('a') örneği içerir
var_dump($result);
?>

Başka bir karşılaştırma işlevi kullanmak isterseniz array_udiff() işlevine bakın.

Notlar

Bilginize:

Bu işlev n boyutlu bir dizinin sadece bir boyutunu karşılaştırır. Daha derinliğine karşılaştırmalar yapmak için array_diff($dizi1[0], $dizi2[0]); sözdizimini kullanabilirsiniz.

Ayrıca Bakınız

  • array_diff_assoc() - Dizilerin farkını hesaplarken ek olarak indisleri de karşılaştırır
  • array_udiff() - Veri karşılaştırması için bir geriçağırım işlevi kullanarak diziler arasındaki farkı bulur
  • array_intersect() - Dizilerin kesişimini hesaplar
  • array_intersect_assoc() - Dizilerin kesişimini hesaplarken ek olarak indisleri de karşılaştırır

add a note

User Contributed Notes 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' => 1);
$aDiff['kenji'] = array('apple' => 1, 'pie' => 1, 'pasta' => 1);
?>

Ok, now some comments about this function:
 - Different from the PHP array_diff, this function DON´T uses the === operator, but the ==, so 0 is equal to '0' or false, but this can be changed with no impacts.
 - This function checks the keys of the arrays, array_diff only compares the values.

I realy hopes that this could help some1 as I´ve been helped a lot with some users experiences. (Just please double check if it would work for your case, as I sad I just tested to a scenario like the one I exposed)

<?php
function arrayRecursiveDiff($aArray1, $aArray2) {
    $aReturn = array();
   
    foreach ($aArray1 as $mKey => $mValue) {
        if (array_key_exists($mKey, $aArray2)) {
            if (is_array($mValue)) {
                $aRecursiveDiff = arrayRecursiveDiff($mValue, $aArray2[$mKey]);
                if (count($aRecursiveDiff)) { $aReturn[$mKey] = $aRecursiveDiff; }
            } else {
                if ($mValue != $aArray2[$mKey]) {
                    $aReturn[$mKey] = $mValue;
                }
            }
        } else {
            $aReturn[$mKey] = $mValue;
        }
    }
   
    return $aReturn;
}
?>
up
43
Jeppe Utzon
13 years ago
If you just need to know if two arrays' values are exactly the same (regardless of keys and order), then instead of using array_diff, this is a simple method:

<?php

function identical_values( $arrayA , $arrayB ) {

    sort( $arrayA );
    sort( $arrayB );

    return $arrayA == $arrayB;
}

// Examples:

$array1 = array( "red" , "green" , "blue" );
$array2 = array( "green" , "red" , "blue" );
$array3 = array( "red" , "green" , "blue" , "yellow" );
$array4 = array( "red" , "yellow" , "blue"