I think you can use the array_filter function to remove null values ββin both arrays and then combine them
$a = array( 'a' => NULL, 'b' => 1, 'c' => 1 ); $b = array( 'a' => 1, 'b' => NULL, 'c' => 1 ); $b = array_filter($b); $a = array_filter($a); $c = array_merge($a, $b); var_dump($c);
This will lead to the conclusion
array(3) { ["b"]=> int(1) ["c"]=> int(1) ["a"]=> int(1) }
LIVE SAMPLE
As a side note, I would add that using array_filter without a second parameter will delete all NULL values, as well as an EMPTY array, etc. If you want to remove only NULL values, you need to use array_filter($yourarray, 'strlen');
EDITED
If you want to keep NULL , if both arrays have it with the same key, and suppose that both arrays have the same number of keys / values, then you will need to loop inside your array and build a new array that keeps NULL where you need to
$a = array( 'a' => NULL, 'b' => 1, 'c' => 1, 'd' => NULL ); $b = array( 'a' => 1, 'b' => NULL, 'c' => 1, 'd' => NULL, ); $c = array(); foreach($a as $key => $val) { if($key == NULL && $b[$key] == NULL) { $c[$key] = $val; } else if($key != NULL && $b[$key] == NULL) { $c[$key]= $val; } else if($key != NULL && $b[$key] != NULL) { $c[$key]= $b[$key]; } else { $c[$key]= $b[$key]; } } var_dump($c);
This will lead to the conclusion
array (size=4) 'a' => int 1 'b' => int 1 'c' => int 1 'd' => NULL
LIVING SAMPLE