Daniel Smith
Daniel Smith

Reputation: 85

Given array keys that correspond to another array, how can I merge them?

I have the following array that is supposed to only be keys:

$keys = ['mod_4_key'];

and the bigger array which contains a lot of information:

$big_array = [ 'mod_4_key' => ['old' => '', 'info' => ''], 'mod_5_key' => ..]

I would like to, based on what is inside $keys generate a new array with the information from $big_array, as such, if we are to compute the "non-difference" between the arrays, the output should be:

$final_array = [ 'mod_4_key' => ['old' => '', 'info' => '']]

I achieved this using a classic foreach but I was wondering if there was no in-built way to achieve this.

Upvotes: 0

Views: 28

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57131

You may be better off with a simple foreach() loop, but there are probably several ways of achieving this.

This uses array_flip() on the $keys, so that you end up with another associative array, then use array_intersect_key() with the big array first.

$final_array = array_intersect_key($big_array, array_flip($keys));

Upvotes: 4

Related Questions