5

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.

Charles
  • 50,943
  • 13
  • 104
  • 142
fonini
  • 3,243
  • 5
  • 30
  • 53
  • there is no built-in function like u looking for...u have to use both loop and 'built-in function for key'. – thumber nirmal Mar 20 '13 at 11:18
  • More duplicates: http://stackoverflow.com/q/2755304/218196, http://stackoverflow.com/q/4780861/218196, http://stackoverflow.com/q/11265133/218196 ... full list: http://stackoverflow.com/search?q=array_intersect_key+is%3Aanswer. – Felix Kling Mar 20 '13 at 11:19

2 Answers2

13
$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];
}
PleaseStand
  • 31,641
  • 6
  • 68
  • 95
  • My real array has float values, so the array_flip function raises the following error: "Can only flip STRING and INTEGER values!" – fonini Mar 20 '13 at 11:18
  • @fonini: In your example, the `$fields` array does not have float values. – Felix Kling Mar 20 '13 at 11:20
  • @FelixKling Sorry about that – fonini Mar 20 '13 at 11:22
  • @fonini: Well, provide a proper example. If `$fields` is really an array of keys, then how can the values (the fields/keys) be floats? As you already noticed, float values cannot be keys. – Felix Kling Mar 20 '13 at 11:23
  • @fonini: This does not change anything for the `$fields` array. I think you applied `array_flip` to the wrong array. Given the example in your question, this answer will work just fine. – Felix Kling Mar 20 '13 at 11:26
  • @FelixKling Man, you're right! I didn't drink enough coffee for today. Thanks! – fonini Mar 20 '13 at 11:29
2

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)));
?>
Tony Stark
  • 8,064
  • 8
  • 44
  • 63