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);
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With