5

$master = ['111' => 'foo', '124' => 'bar', '133' => 'baz'];

$check = ['111' => 14, '133' => 23 ]';

I want to remove all keys from $master that do not exists in $check. So the result in this example should be:

$newMaster = ['111' => 'foo', '133' => 'baz'];

Any idea how to do this ? Thanks in advance.

4
  • 2
    array_intersect by keys <- remove 3 characters (excluding spaces :) and add an underscore to it, and you have your answer: array_intersect_key Commented Jan 11, 2016 at 12:14
  • Partial dupe: stackoverflow.com/q/11644267/3933332 (Just without the flipping of the second array) Commented Jan 11, 2016 at 12:16
  • 1
    @Rizier123 five characters to be painfully precise ;-) Commented Jan 11, 2016 at 12:16
  • 2
    @Havelock I excluded the spaces, so by and the s from keys = 3 ;) Commented Jan 11, 2016 at 12:17

3 Answers 3

4

Yes, simply use array_intersect_key()

$newMaster = array_intersect_key($master, $check);
Sign up to request clarification or add additional context in comments.

Comments

0

Yeah you can simply use:

var_dump(array_intersect_key($master, $check));

Comments

0
$master = ['111' => 'foo', '124' => 'bar', '133' => 'baz'];

$check = ['111' => 14, '133' => 23 ];


$intersectArray = array_intersect_key($master, $check);

Here key will compare using array_intersect_key() function it will compare your $check key in $master and give you result where $check key is matched in $master and you got output ['111' => 'foo', '133' => 'baz']; in $intersectArray

For more details you will check this link http://php.net/manual/en/function.array-intersect-key.php

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.