2

I have 2 arrays.

<?php
$array1 = array('id' => 1, 'email' => '[email protected]' , 'name' => 'john' );
$array2 = array('id', 'email');

i am having trouble writing a code to unset the key value pair from array1 that is not from array 2.

The problem with this is unlike most examples, my array2 does not have a format of a key value pair but only key.

How do i go about removing things from array1 that is not specified in array2.

my current code is not working

foreach ($array1 as $key => $value) {
if (array_search($key, $array2)===false) {
 unset($key);
}
}
1
  • Any string keys or values in your array should be enclosed in quotes so john should be 'john' Commented Apr 1, 2014 at 8:27

3 Answers 3

6

Use array_diff_key() to leave values which are not in second array:

$array1 = array('id'=>1, 'email'=> 'email' , 'name'=>'john' );
$array2 = array('id','email');

$result = array_diff_key($array1, array_flip($array2));

Or, if you want to change first array:

$array1 = array_diff_key($array1, array_flip($array2));

Edit (misunderstanding)

Use array_intersect_key() to leave values which are in second array:

$array1 = array_intersect_key($array1, array_flip($array2));
Sign up to request clarification or add additional context in comments.

9 Comments

Please, leave a comment if dv - that would be appreciated
Maybe they did since the answer is not complete.
And I edited it also - because no sense in loop if we can avoid it (and write directly to first array)
array_flip() is needed because your second array contains values, not keys. It's like [0=>'id', 1=>'email'] so it's keys are 0 and 1 while for array_diff_key() you need to pass array with keys to get difference
One more thing is that as I Can Has Cheezburger mentioned, i want to output items that are specified in $array2. So the function used should be array_intersect_key instead of array_diff_key
|
5

You are doing it right, just that your way of unset is incorrect:

unset($key);

should be

unset($array1[$key]);

Demo

Comments

0

You have to unset the element by its index (starting from 0) For example unset($array2[1]); will remove the 'email' element.

So in Your case it should be: unset($array1[$key]);

Comments

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.