Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between two arrays

Tags:

php

I have following two arrays. I want the difference between these two arrays. That is, how can I find the values that do not exist in both arrays?

 $array1=Array ( [0] => 64 [1] => 98 [2] => 112 [3] => 92 [4] => 92 [5] => 92 ) ;  $array2=Array ( [0] => 3 [1] => 26 [2] => 38 [3] => 40 [4] => 44 [5] => 46 [6] => 48 [7] => 52 [8] => 64 [9] => 68 [10] => 70 [11] => 72 [12] => 102 [13] => 104 [14] => 106 [15] => 92 [16] => 94 [17] => 96 [18] => 98 [19] => 100 [20] => 108 [21] => 110 [22] => 112); 
like image 945
user1178695 Avatar asked Apr 09 '12 18:04

user1178695


People also ask

How do I compare two arrays of arrays?

Using Arrays. equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method. Using Arrays. deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.

How will you find the difference between two array using array function explain?

The array_diff() function compares the values of two (or more) arrays, and returns the differences. This function compares the values of two (or more) arrays, and return an array that contains the entries from array1 that are not present in array2 or array3, etc.

Can we compare two arrays in JavaScript?

While JavaScript does not have an inbuilt method to directly compare two arrays, it does have inbuilt methods to compare two strings. Strings can also be compared using the equality operator. Therefore, we can convert the arrays to strings, using the Array join() method, and then check if the strings are equal.


1 Answers

To get the difference between the two arrays you need to do the following:

$fullDiff = array_merge(array_diff($array1, $array2), array_diff($array2, $array1)); 

The reason being that array_diff() will only give you the values that are in $array1 but not $array2, not the other way around. The above will give you both.

like image 102
Crashspeeder Avatar answered Oct 12 '22 14:10

Crashspeeder