Return only the values ​​of the array that it has in another array

I have two arrays that look like this:

$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 built-in PHP function that retrieves an array filled only with the keys specified in the $fieldsarray (id, name, city, birthday, money)?

Expected Return:

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

PS: I am only looking for a built-in function.

+5
source share
2 answers
$values2 = array_intersect_key($values, array_flip($fields));

If keys should always be returned in order $fields, use a simple loop foreach:

$values2 = array();
foreach ($fields as $field) {
    $values2[$field] = $values[$field];
}
+13
source

array_intersect_key - Computes the intersection of arrays using keys for comparison

<?php
$fields = array('id', 'name', 'city', 'birthday');

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

var_dump(array_intersect_key($fields, array_flip($values)));
?>
+2
source

All Articles