PHP array_merge empty is always less

My goal is to combine 2 different arrays.

I have a table "a" and "b". The data from table "a" are more reliable.

PROBLEM : if the key from "a" contains an empty value, I would like to take it from table "b".

Here is my code:

<?php $a = array('key1'=> "key1 from prioritar", 'my_problem'=> ""); $b = array('key1'=> "key1 from LESS prioritar", 'key2'=>"key2 from LESS prioritar", 'my_problem'=> "I REACHED MY GOAL!"); $merge = array_merge($b, $a); var_dump($merge); 

Is there a way to do this in one function without doing something like below?

 foreach($b as $key => $value) { if(!array_key_exists($key, $a) || empty($a[$key]) ) { $a[$key] = $value; } } 
+6
source share
2 answers

You can use array_replace and array_filter

 $mergedArray = array_replace($b, array_filter($a)); 

Result:

 array(3) { ["key1"]=> string(19) "key1 from prioritar" ["key2"]=> string(24) "key2 from LESS prioritar" ["my_problem"]=> string(18) "I REACHED MY GOAL!" } 
+5
source

Just array_filter () $a , which will remove any element with a '' value.

 $merge = array_merge($b, array_filter($a)); 
+2
source

All Articles