Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get certain elements of an array by its key

Tags:

arrays

php

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)

like image 278
Xaver Avatar asked Nov 28 '13 14:11

Xaver


1 Answers

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

like image 77
Amal Murali Avatar answered Sep 27 '22 16:09

Amal Murali