5

I'm sure there's a function for this:

What I have:

$myArray = array( 'foo' => 123, 'bar' => 456, 'lou' => 789, 'wuh' => 'xyz' );
$iNeed = array( 'foo', 'lou' );

How can I get the key value pairs that $iNeed:

$output = super_magic_function( $iNeed, $myArray );
// output should be array( 'foo' => 123, 'lou' => 789 );

How is that super_magic_function called (native php if possible)

4
  • Why can`t you make it...? Commented Nov 28, 2013 at 14:49
  • Why don't you try something, and then if it does not work and you can't figure out why, we find that for you Commented Nov 28, 2013 at 14:50
  • @HenkJansen I've tried with ´array_intersect´ but got an empty array Commented Nov 28, 2013 at 14:52
  • @AmazingDreams array_combines parameters must have equal number of elements Commented Nov 28, 2013 at 15:00

1 Answer 1

6
$output = array_intersect_key($myArray, array_flip($iNeed));

If you need it as a function:

function super_magic_function($array, $required) {
    return array_intersect_key($array, array_flip($required));
}

Output:

Array
(
    [foo] => 123
    [lou] => 789
)

Documentation: array_intersect_key(), array_flip()

Demo.

Sign up to request clarification or add additional context in comments.

3 Comments

Genius! That's what I'm searching for
Wow - the demo is the icing on the cake!
Haha. I'm glad to have been of help. Cheers :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.