4

Given:

$data = array(
    "some"  => "163",
    "rand"  => "630",
    "om"    => "43",
    "words" => "924",
    "as"    => "4",
    "keys"  => "54"
);

I want a new array using only the keys that match those certain keys:

$keys = array( "some", "thing", "rand", "keys" );

I'd like to return an array with those keys in common, creating:

$arr = array(
     "some"   => "163",
     "rand"   => "630",
     "keys"   => "54"
);
Alex V
  • 18,176
  • 5
  • 36
  • 35

3 Answers3

7

You can do this with array_intersect_key() and array_flip():

$arr = array_intersect_key($data, array_flip($keys));

Result:

Array
(
    [some] => 163
    [rand] => 630
    [keys] => 54
)
1
$filteredArray = array_intersect_key($data, array_flip($keys)); 

is the easiest solution,

but just to be different:

$data = array(
    "some"  => "163",
    "rand"  => "630",
    "om"    => "43",
    "words" => "924",
    "as"    => "4",
    "keys"  => "54"
);

$keys = array( "some", "thing", "rand", "keys" );

$filteredArray = array_filter($data,function($item) use (&$data,$keys) { $retVal = false; if (in_array(key($data),$keys)) $retVal = true; next($data); return $retVal; });

var_dump($filteredArray);
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
0
$result = array_intersect_key($data, array_flip($keys));
goat
  • 31,486
  • 7
  • 73
  • 96