I have these two arrays:
$list = [
'fruit' => [],
'animals' => [],
'objects' => [],
];
$dataArray = [
'fruit' => 'apple',
'animals' => ['dog', 'cat'],
'asd' => 'bla'
];
I want to merge them so that $list at the end is:
[fruit] => Array
(
[0] => apple
)
[animals] => Array
(
[0] => dog
[1] => cat
)
[objects] => Array
(
)
so, things to pay attention to:
- even if 'fruit' had only one element, is still an array in $list
- keys missing from $list ('asd' key) are simply ignored
- keys with no values are still kept, even if empty
Using array_merge doesn't work:
$merged = array_merge($list, $dataArray);
[fruit] => apple
[animals] => Array
(
[0] => dog
[1] => cat
)
[objects] => Array
(
)
[asd] => bla
I managed to get what I want with this:
foreach ($dataArray as $key => $value) {
if (isset($list[$key])) {
if (is_array($value)) {
$list[$key] = $value;
}
else {
$list[$key] = [$value];
}
}
}
But I was wondering if there was a cleaner way to do it or some other php function that I'm not aware of.
array_walk()
you can however use your loop wrapped in a function and it will do all the stuff but there exists no build in function that does all what you want. – Chukker