Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - How to compare two arrays and remove duplicate values

Tags:

So this is whats bothering me.

I have two arrays:

$array1 = array('[param1]' ,'demo' ,'[param2]' ,'some' ,'[param3]'); $array2 = array('value1'   ,'demo' ,'value2'   ,'some' ,'value3'); 

Now I want to compare these two array's, and remove all duplicate values.
At the end I want this two array-s but without 'demo' and 'some' values in them.
I want to remove all values from array-s that have the same index key and value.
Array's will always have same number of values and indexes, I only want to compare them and remove entries that have the same index key and value, from both of them.

I'm doing something like this now:

$clean1 = array(); $clean2 = array();      foreach($array1 as $key => $value) {     if($value !== $array2[$key])     {         $clean1[$key] = $value;         $clean2[$key] = $array2[$key];     } }  var_export($clean1); echo "<br />"; var_export($clean2); 

And this works! But im wondering is there any other way of doing this? Maybe without using foreach loop? Is there more elegant way of doing this?

like image 987
Limeni Avatar asked Jan 01 '12 00:01

Limeni


People also ask

How can I get duplicate values from two arrays in PHP?

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

How do you remove duplicates from an array in PHP?

The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed.

How can I find the difference between two arrays in PHP?

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.


2 Answers

You can use the function array_diff in PHP that will return and array containing the keys that are the same between the two arrays.

$clean1 = array_diff($array1, $array2); 

http://php.net/manual/en/function.array-diff.php

like image 35
Shawn Janas Avatar answered Sep 21 '22 16:09

Shawn Janas


array_unique( array_merge($arr_1, $arr_2) ); 

or you can do:

$arr_1 = array_diff($arr_1, $arr_2); $arr_2 = array_diff($arr_2, $arr_1); 

i guess...

like image 60
Mr. BeatMasta Avatar answered Sep 18 '22 16:09

Mr. BeatMasta