1

I have array like this:

$user = [
'id' => 1,
'fname' => 'name1',
'lname' => 'lname',
'age' => 20
];

I want to get values by given keys. Is there function already.

$userData = array....($user, ['fname', 'lname']); // get only fname and lname from user

I dont want to to for loops or similar.

Thanks

user2693928
  • 3,507
  • 2
  • 14
  • 25
  • does `array_filter` fine? with ARRAY_FILTER_USE_KEY. Look at https://stackoverflow.com/questions/4260086/php-how-to-use-array-filter-to-filter-array-keys – dWinder Mar 19 '19 at 05:40
  • Without looping, it isn't possible. You may use functions but they do the same under the hood. Maybe you are looking for an elegant solution. – nice_dev Mar 19 '19 at 05:41
  • refrence here http://php.net/manual/en/function.array-intersect-key.php – Mohammad Malek Mar 19 '19 at 05:54

1 Answers1

5

You can use array_intersect_key, after flipping the second array to an associative array.

$userData = array_intersect_key($user, array_flip(['fname', 'lname']));
Barmar
  • 669,327
  • 51
  • 454
  • 560
  • Thanks, that was I was looking for, even though php creaters could create more descriptive function – user2693928 Mar 19 '19 at 05:47
  • 3
    I don't think this is a common operation. The function you want doesn't exist in JavaScript or Python, either. – Barmar Mar 19 '19 at 05:49