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