PHP: How to overwrite values in one array with values from another without adding new keys to the array? -
I have an array with the default settings, and there is an array with user-specified settings. I want to merge these two arrays so that the default setting with the user-specified one is overwritten.
I tried to use array_merge , which overwrites like I like, but it also adds new settings if the user has specified the settings that default ones Are not present in Is this a better function that I can use with array_merge ? Or is there a function that I can use to filter user-specified arrays so that it only sets the key that is present in the default settings array?
What I need / P>
$ default = array ('a' => 1, 'b' => 2); $ User = array ('b' => 3, 'c' => 4); // Merging $ user by default in the default so that we end it: Array ([a] = & gt; 1 [b] = & gt; 3) You can actually add two arrays instead of using array_merge ( $ user + $ Default )
If you want to stop any user settings that are not present in the default that you can use:
array 1's Returns an associative array containing all entries Example:
$ default = array ('a' = & gt; 1, 'b'), whose keys are present in all arguments= & Gt; 2); $ User = array ('b' => 3, 'c' => 4); // $ default Add any setting from the user, then select only the key in both arrays $ settings = array_intersect_key ($ user + $ default, $ default); Print_r ($ settings);
Result:
array ([b] => 3 [a] = & gt; 1)The key / value (and the order) has already been selected from
$ user, this is the reason that in thebarray the firstaFirst comes theoneis not$ userin the$ userany keys defined in the$ user $ . >. You can then remove any key in$ user + $ default, which are not defined in$ default.
Comments
Post a Comment