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.
$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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With