1

There is a full array and a specific array.

I want to get only parts that fit a particular in the entire array.

For example, I have two arrays.

$all_array = array('a'=>'1', 'b'=>'2', 'c'=>'3', 'd'=>'4', 'e'=>'5')

$find_array = array('b', 'd', 'e')

Then, I want to get $result_array

array('b'=>'2', 'd'=>'4', 'e'=>'5'); or array('2', '4', '5');

Is there a way to get result?

Chang Seob. Kim
  • 301
  • 3
  • 13

3 Answers3

1

One liner array_intersect_key($all_array, array_flip($find_array));

GMarco24
  • 410
  • 3
  • 10
  • Look the same as https://stackoverflow.com/a/4260168/6487675 ... – dWinder Jun 13 '19 at 08:52
  • Oh, pardon me. Next time I'll search entire stackoverflow in order not to make duplicate answer – GMarco24 Jun 13 '19 at 08:56
  • Not meant to offence - this is the first answer when doing google search on filter array by key (and in my opinion is the best solution here). And I also think that this question title is to general for the question itself - this title suggest the answer will be array_filter which takes function as argument – dWinder Jun 13 '19 at 09:00
0

you can use array_walk

$r=[];
array_walk($find_array, function($v,$k) use($all_array,&$r){$r[$v] = $all_array[$v];});

DEMO

Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20
0

foreach() the $find_array and check in $all_array, if exist, store it in new array.

$all_array = array('a'=>'1', 'b'=>'2', 'c'=>'3', 'd'=>'4', 'e'=>'5');

$find_array = array('b', 'd', 'e');
$new = array();
foreach($find_array as $val){
    if(isset($all_array[$val])){
        $new[$val] = $all_array[$val];
    }
}
print_r($new);

Demo

Bhaskar Jain
  • 1,651
  • 1
  • 12
  • 20