Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Array Keys to create a New Array

Tags:

arrays

php

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"
);
like image 754
Alex V Avatar asked Feb 23 '23 00:02

Alex V


1 Answers

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
)
like image 199
Tim Cooper Avatar answered Mar 06 '23 18:03

Tim Cooper