Hướng dẫn php array diff

[PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8]

array_diffComputes the difference of arrays

Description

array_diff[array $array, array ...$arrays]: array

Parameters

array

The array to compare from

arrays

Arrays to compare against

Return Values

Returns an array containing all the entries from array that are not present in any of the other arrays. Keys in the array array are preserved.

Changelog

VersionDescription
8.0.0 This function can now be called with only one parameter. Formerly, at least two parameters have been required.

Examples

Example #1 array_diff[] example

Multiple occurrences in $array1 are all treated the same way. This will output :

Example #2 array_diff[] example with non-matching types

Two elements are considered equal if and only if [string] $elem1 === [string] $elem2. That is, when the string representation is the same.

To use an alternate comparison function, see array_udiff[].

Notes

Note:

This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff[$array1[0], $array2[0]];.

See Also

  • array_diff_assoc[] - Computes the difference of arrays with additional index check
  • array_udiff[] - Computes the difference of arrays by using a callback function for data comparison
  • array_intersect[] - Computes the intersection of arrays
  • array_intersect_assoc[] - Computes the intersection of arrays with additional index check

nilsandre at gmx dot de

15 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.

Anonymous

16 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.

james dot PLZNOSPAM at bush dot cc

5 years ago

If you want a simple way to show values that are in either array, but not both, you can use this:



If you want to account for keys, use array_diff_assoc[] instead; and if you want to remove empty values, use array_filter[].

Prakashgun

4 years ago

If duplicate value comes in the first array, that will be also included. See in the output "blue" comes twice.

wrey75 at gmail dot com

7 years ago

The difference is made only on the first level. If you want compare 2 arrays, you can use the code available at //gist.github.com/wrey75/c631f6fe9c975354aec7 [including a class with an function to patch the array]

Here the basic function:

function my_array_diff[$arr1, $arr2] {
        $diff = array[];

                // Check the similarities
        foreach[ $arr1 as $k1=>$v1 ]{
            if[ isset[ $arr2[$k1]] ]{
                $v2 = $arr2[$k1];
                if[ is_array[$v1] && is_array[$v2] ]{
                    // 2 arrays: just go further...
                    // .. and explain it's an update!
                    $changes = self::diff[$v1, $v2];
                    if[ count[$changes] > 0 ]{
                        // If we have no change, simply ignore
                        $diff[$k1] = array['upd' => $changes];
                    }
                    unset[$arr2[$k1]]; // don't forget
                }
                else if[ $v2 === $v1 ]{
                    // unset the value on the second array
                    // for the "surplus"
                    unset[ $arr2[$k1] ];
                }
                else {
                    // Don't mind if arrays or not.
                    $diff[$k1] = array[ 'old' => $v1, 'new'=>$v2 ];
                    unset[ $arr2[$k1] ];
                }
            }
            else {
                // remove information
                $diff[$k1] = array[ 'old' => $v1 ];
            }
        }

                // Now, check for new stuff in $arr2
        reset[ $arr2 ]; // Don't argue it's unnecessary [even I believe you]
        foreach[ $arr2 as $k=>$v ]{
            // OK, it is quite stupid my friend
            $diff[$k] = array[ 'new' => $v ];
        }
        return $diff;
    }

ds2u at the hotmail dot com

19 years ago

Yes you can get rid of gaps/missing keys by using:



But to drop the storage of void spaces [actually a line feed] which are irritatingly indexed when reading from files - just use difference:



dst

emeka dot echeruo at gmail dot com

6 years ago

Resubmitting... the update for takes into account comparison issues 
Computes the difference of all the arrays

Simon Riget at paragi.dk

16 years ago

A simple multidimentional key aware array_diff function.

   

This function meets my immidiate needs but I'm shure it can be improved.

vojtech dot hordejcuk at gmail dot com

12 years ago

Based on one lad's code, I created following function for creating something like HTML diff. I hope it will be useful.

javierchinapequeno at yahoo dot es

11 years ago

Hi, I´d like to give a piece of advice to all who need to use this function to compare two arrays that have a great quantity of elements. You should sort both arrays first before comparing, it will work faster.
Thanks

Anonymous

12 years ago

Hi!
I tried hard to find a solution to a problem I'm going to explain here, and after have read all the array functions and possibilities, I had to create what I think should exist on next PHP releases.

What I needed, it's some kind of Difference, but working with two arrays and modifying them at time, not returning an array as a result with the diference itself.

So, as an example:

A = 1,2,3
B = 2,3,4

should NOT be:

C = 1,4

but:

A = 1
B = 4

so basically, I wanted to delete coincidences on both arrays.

Now, I've some actions to do, and I know wich one I've to do with the values from one array or another.
With the normal DIFF I can't, because if I've an array like C=1,4, I dont know if I've to do the Action_A with 1 or with 4, but I really know that everything in A, will go to the Action_A and everithing in B, will go to Action_B. So same happens with 4, don't know wich action to apply...

So I created this:



This cute, works by reference, and modifies the arrays deleting coincidences on both, and leaving intact the non coincidences.

So a call to this will be somethin' like:



And HERE, I'll have my arrays as I wanted:

$original = 1
$new = 4

Now, why I use it precisely?

Imagine you've some "Events" and some users you select when create the event, can "see" this event you create. So you "share" the event with some users. Ok?

Imagine you created and Event_A, and shared with users 1,2,3.

Now you want to modify the event, and you decide to modify the users to share it. Imagine you change it to users 2,3,4.

[numbers are users ID].

So you can manage when you are going to modify, to have an array with the IDs in DDBB [$original], and then, have another array with ID's corresponding to the users to share after modifying [$new]. Wich ones you've to DELETE from DDBB, and wich ones do you've to INSERT?

If you do a simple difference or somehow, you get somethin' like C=1,4.
You have no clue on wich one you've to insert or delete.

But on this way, you can know it, and that's why:

- What keeps on $original, it's somethin not existing in $new at the beggining. So you know that all what you've inside $original, have to be deleted from DDBB because what you did in the modifying process, it's to unselect those users keeping in $original.
- What keeps on $new, it's something not existing in $original at the beggining. Wich means that in the modifying process you added some new users. And those have to be inserted in DDBB. So, everything keeping inside $new, have to be inserted in the DDBB.

Conclusion:

- Remaining in $original --> delete from DB.
- Remaining in $new --> insert into DB.

And that's all!

I hope you find it useful, and I encourage PHP "makers", to add in a not distant future, somethin' like this one natively, because I'm shure that I'm not the first one needing something like this.

Best regards all,

Light.

gilthans at NOgmailSPAM dot com

15 years ago

I needed a function to only remove the element the amount of times he appears in the second array. In other words, if you have Array[1, 1, 2] and Array[1], the return value should be Array[1, 2].
So I built this function right here:

Chủ Đề