7

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.

2

2 Answers 2

14
$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];
}
Sign up to request clarification or add additional context in comments.

6 Comments

My real array has float values, so the array_flip function raises the following error: "Can only flip STRING and INTEGER values!"
@fonini: In your example, the $fields array does not have float values.
@FelixKling Sorry about that
@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.
@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.
|
3

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)));
?>

3 Comments

I am little late to post the answer....
You still need to flip the fields ...
+1 for the quick correction ...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.