Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return only array values which it's keys are in another array [duplicate]

Tags:

arrays

php

I have two arrays which looks like:

$fields = array('id', 'name', 'city', 'birthday', 'money');

$values = array('id' => 10,    
    'name' => 'Jonnas',   
    'anotherField' => 'test',
    'field2' => 'aaa',
    'city' => 'Marau', 
    'field3' => 'bbb',
    'birthday' => '0000-00-00',
    'money' => 10.95
);

Is there a PHP built-in function which retrieves an array filled only with the keys specified on $fields array (id, name, city, birthday, money)?

The return I expect is this:

$values2 = array(
    'id' => 10,
    'name' => 'Jonnas',
    'city' => 'Marau',
    'birthday' => '0000-00-00',
    'money' => 10.95
);

P.S.: I'm looking for a built-in function only.

like image 222
fonini Avatar asked Mar 20 '13 11:03

fonini


1 Answers

$values2 = array_intersect_key($values, array_flip($fields));

If the keys must always be returned in the order of $fields, use a simple foreach loop instead:

$values2 = array();
foreach ($fields as $field) {
    $values2[$field] = $values[$field];
}
like image 177
PleaseStand Avatar answered Nov 02 '22 22:11

PleaseStand