I have an array with default settings, and one array with user-specified settings. I want to merge these two arrays so that the default settings gets overwritten with the user-specified ones.
I have tried to use array_merge, which does the overwriting like I want, but it also adds new settings if the user has specified settings that doesn’t exist in the default ones. Is there a better function I can use for this than array_merge? Or is there a function I can use to filter the user-specified array so that it only contains keys that also exist in the default settings array?
Example of what I want
$default = array('a' => 1, 'b' => 2);
$user = array('b' => 3, 'c' => 4);
// Somehow merge $user into $default so we end up with this:
Array
(
[a] => 1
[b] => 3
)
You can actually just add two arrays together (
$user+$default) instead of usingarray_merge.If you want to stop any user settings that don’t exist in the defaults you can use
array_intersect_key:Example:
Results:
The keys/values (and order) are selected first from
$userin the addition, which is whybcomes beforeain the array, there is noain$user. Any keys not defined in$userthat are defined in$defaultwill then be added to the end of$user. Then you remove any keys in$user + $defaultthat aren’t defined in$default.