Lets say you are having a user provide information.
Array 1
But not all is required. So you have defaults.
Array 2
Does PHP have a function which will overwrite all array values of Array 2
based on if they are supplied in Array 1
, and not empty?
The array_merge() is a builtin function in PHP and is used to merge two or more arrays into a single array. This function is used to merge the elements or values of two or more arrays together into a single array.
The array_merge() function merges one or more arrays into one array. Tip: You can assign one array to the function, or as many as you like. Note: If two or more array elements have the same key, the last one overrides the others.
Definition and Usage 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.
The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
If you just want to keep the options that you expect and discard the rest you may use a combination of array_merge
and array_intersect_key
.
<?php
function foo($options) {
$defaults = [
'a' => 1,
'b' => null,
];
$mergedParams = array_merge(
$defaults,
array_intersect_key($options, $defaults)
);
return $mergedParams;
}
var_dump(foo([
'a' => 'keep me',
'c' => 'discard me'
]));
// => output
//
// array(2) {
// ["a"]=>
// string(7) "keep me"
// ["b"]=>
// NULL
// }
If you instead want to keep any extra key then array_merge($defaults, $options)
will do just fine.
$defaults = array(
'some_key_1'=>'default_value_1',
'some_key_2'=>'default_value_2',
);
$inputs = array_merge($defaults, $inputs)
Note that if the $inputs array contains keys not in the $defaults array they will be added in the result.
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