PHP merging two arrays, improving the code
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
Total Views: 42 Today Views: 0















