My goal is to merge 2 different arrays.
I have table "a" & "b". Data from table "a" are more prioritar.
PROBLEM: if a key from "a" contains an empty value, I would like to take the one 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;
}
}
The array_merge_recursive() function merges one or more arrays into one array. The difference between this function and the array_merge() function is when two or more array elements have the same key. Instead of override the keys, the array_merge_recursive() function makes the value as an array.
Description ¶ Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array. If the input arrays have the same string keys, then the later value for that key will overwrite the previous one.
You can use array_replace
and array_filter
$mergedArray = array_replace($b, array_filter($a));
The result would be:
array(3) {
["key1"]=>
string(19) "key1 from prioritar"
["key2"]=>
string(24) "key2 from LESS prioritar"
["my_problem"]=>
string(18) "I REACHED MY GOAL!"
}
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