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

3

1 Answer 1

4

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

$userData = array_intersect_key($user, array_flip(['fname', 'lname']));
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that was I was looking for, even though php creaters could create more descriptive function
I don't think this is a common operation. The function you want doesn't exist in JavaScript or Python, either.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.