-3

Possible Duplicate:
PHP Built-in Method to Get Array Values Given a List of Keys

Does PHP has built-in function for this purpuse?

I have two arrays, first associative with some data. For example:

$data = array(
    'name'      => 'John',
    'last_name' => 'Smith',
    'address'   => 'NY, ...',
    'phone'     => '1234567'
);

And another array with keys:

$keys = array(
    'name', 
    'last_name'
);

After aplying this function I get only values from first array, which have keys from second array.

$result = function($data, $keys);
print_r($result);

// array(
//    'name'      => 'Jonh',
//    'last_name' => 'Smith'
// )
2

2 Answers 2

6

Try the below:

$result = array_intersect_key($data, array_fill_keys($keys, null));
Sign up to request clarification or add additional context in comments.

Comments

3
 $data = array(
      'name'      => 'John',
      'last_name' => 'Smith',
      'address'   => 'NY, ...',
      'phone'     => '1234567'
  );

  $keys = array('name', 'last_name');

 print_r(array_intersect_key($data, array_flip($keys)));

8 Comments

Care to comment your code, explain why you propose this snippet
@Yaroslav I proposed this snippet because it prints out the desired array and hence solves the question. Isn't StackOverflow about this? Why the downvote- do I miss something?
Steffen, yes, SO is about coding and some code is better than nothing. But if you comment your code it will be even more useful to the OP or any other future visitors, they will have a better understanding of it. Check this metaSO question and Jon Skeet: Coding Blog on how to give a correct answer. And for the downvote, it is anonymous so I can't tell you who downvoted, but is not mine for sure ;)
@Yaroslav Yes, to make my commentation as complete as the accepted and upvoted answer, I should have added a "Try the code below" (to make sure, the reader know it's not "Don't try the below" or "Ignore this post, there's no answer in it"). The article you mentioned states "Code is King- make sure it compiles" and "Code without an explanation is rarely useful, however". Mine is runnable. Since the OP just asked for the name of one concrete function I actually think commentary is negligible here. Different opinions. I find it sad, when correct answers are not honored but devalued.
I can't try the code, I'm not a php developer, so I can't upvote to contrarest the downvote you already have as I don't know if your code compiles or not. If you had some comments maybe, for example, I could have a better understanding of what are you doing and how you are doing it and then I could think "ok, I can't try the code but the reasoning is correct, let me upvote it". And last but not least. Yes, the accepted answer has only a "Try the below". So then you will not comment? Just because others don't comment?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.