0

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

  1. merge array1 and array2 overwriting array2 with values of array1, and adding missing keys.

  2. merge $array1 with $array2 overwritting $array2 with values from $array1, yet neglect extra data in array1 (above example should neglect name)

  3. how can i unset all array_keys from $array1 which is in $filter

  4. 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

1
  • I'm very unclear about what some of these operations should accomplish. Please give expected results for each question. Commented Mar 9, 2014 at 1:55

1 Answer 1

2

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]);
});
Sign up to request clarification or add additional context in comments.

3 Comments

$a1 = array_filter($a1, function($var) use($filter) { return in_array($var, $filter) ? true : false; }); and this solve 3, and 4 if there was no keys.
not sure if my answers for 3 & 4 are the best.. There has to be a better way
@Zalaboza - did I pass your test?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.