1

If I have an array that has more info than I need and I want to pull out a subset of its name value pairs I have come up with 2 methods.

Both rely on this:

  $detailkeys=array(title,summary,subtitle,url,imgsrc,description);

The method I came up with on my own:

  foreach ($detailkeys as $keyname) {
    $details[$keyname]=$data[$keyname];
  }

The method I found online:

  // get just the desired parts of $data and put them in $details.
  $details=array_intersect_key($data, array_flip($detailkeys)); 

The second method, with a decent comment, is what I chose, but wanted to see what anyone else had to say about it.

1

I think the second method is preferable. And this would seem perfectly readable, providing you are familiar with the array_intersect_key() function (although that's a quick lookup if you're not, and if you are it's almost self documenting). To be honest, I think your first method would also require a similar comment.

The second method also avoids an additional $keyname variable. And with it being a built-in function you would expect it to be optimised.

Have you tried benchmarking the results? (Although TBH with such a small set of "required" keys I can't imagine this being significant - I micro optimisation at best.)

You could perhaps avoid the need for your $detailkeys if you initialised your $details array with the required keys to begin with (if that is possible)...

$details = array (
    'title' => null,
    'summary' => null,
    // etc.
);

And then you also wouldn't need to call array_flip()...

$details = array_intersect_key($data, $details);

However, I would also query whether you needed to create a subset array to begin with. If you are only reading the data, passing it around, and not changing it, then it's not necessarily an optimisation and could even be the opposite.

| improve this answer | |
  • I'm actually pulling k=>v pairs out of post to send to a function that expects an array. I don't want to send the full $_POST array to the function. I could do it as you suggest and avoid both the $detailkeys array and the call to array_flip() – TecBrat Jan 15 '14 at 20:47
  • I think the only reason I questioned this is because I hadn't fully grasped that array_intersect_key() was built for exactly this situation. – TecBrat Jan 15 '14 at 21:40
  • Yes, it certainly goes against the grain to pass the $_POST array, but that is usually because it contains unsanitized data. Minor point, but... unless you change the passed array inside the function then your method of copying the necessary elements first is actually going to use slightly more memory (PHP's copy-on-write). – MrWhite Jan 15 '14 at 22:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.