I have the following tested code that after a couple of tries does the job to filter unique results out of two merged arrays. I previously tried using array_diff, array_diff_key, array_diff_assoc to no avail until I settled with the following.
- The second needs to first exclude empty values (like 0) using array_filter, otherwise empty values (“red” => “0”) are also printed in the merged result which is not expected.
- array_unique removes duplicates from the merge.
So the following is working as expected, but I wonder if there is any betterment to the code which looks a bit like winding around. I meant I am not confident if the code is properly done:
$array1 = array("a" => "green", "b" => "purple", "blue" => "0");
$array2 = array("a" => "0", "b" => "purple", "blue" => "blue", "red" => "0");
$merge = array_unique(array_merge($array1, array_values(array_filter($array2))));
Any betterment is much appreciated. Thanks
UPDATE:
Sorry, I was evolving late in the requirement, that later I realized I should also consider replacing the first array1 with array2 even when NULL return when pairs exists in both. I had better go back to my drawing room. Thanks
I din get what exactly you want, but as per your codes result, i guess this or something like this will work for you.
$merge = $array1 + array_filter($array2);