Reputation: 9007
i need this a lot and i was thinking there must be a way to avoid looping arrays to accomplish this task.
example arrays
$array1 = ['user_id'=>'1','password'=>'PASS','name'=>'joe','age'=>'12'];
$array2 = ['user_id'=>'0','password'=>'default','age'=>'21'];
$filter = ['user_id','password'];
Question is how can i
merge array1 and array2 overwriting array2 with values of array1, and adding missing keys.
merge $array1
with $array2
overwritting $array2
with values from $array1
, yet neglect extra data in array1 (above example should neglect name)
how can i unset all array_keys from $array1
which is in $filter
how to only return part of the array from $array1
where keys exist in $filter
without using loops ?
sorry if i ask for alot, but this is meant to collect most usages of array_intersect , array_merge, and array_diff and how to use them correctly.
edit:
Expected output
for 1.
['user_id'=>'1','password'=>'PASS','name'=>'joe','age'=>'12']; //since all array2 was overwritten and extra keys was added
2.
['user_id'=>'1','password'=>'PASS','age'=>'12'];
3.
['age'=>'21']; //removed user_id,password from array1 since they exist in $filter
4.
['user_id'=>'1','password'=>'PASS','age'=>'12'];//return only values of keys that exist in $filter
thanks
Upvotes: 0
Views: 1870
Reputation: 3070
1-merge array1 and array2 overwriting array2 with values of array1, and adding missing keys.
$a1 = $a1 + $a2;
2-merge $array1 with $array2 overwritting $array2 with values from $array1, yet neglect extra data in array1 (above example should neglect name)
$a2 = $a2 + $a1;
3-how can i unset all array_keys from $array1 which is in $filter
array_walk($array1, function($val,$key) use(&$array1, $filter) {
if(in_array($key, $filter)) unset($array1[$key]);
});
4-how to only return part of the array from $array1 where keys exist in $filter
array_walk($array1, function($val,$key) use(&$array1, $filter) {
if(!in_array($key, $filter)) unset($array1[$key]);
});
Upvotes: 2