PHP: How to compare keys in one array with values ​​in another and return matches?

I have the following two arrays:

$array_one = array('colorZero'=>'black', 'colorOne'=>'red', 'colorTwo'=>'green', 'colorThree'=>'blue', 'colorFour'=>'purple', 'colorFive'=>'golden'); $array_two = array('colorOne', 'colorTwo', 'colorThree'); 

I want an array from $array_one that contains only key-value pairs whose keys are members of $ array_two (either by creating a new array or removing the rest of the elements from $array_one )

How can i do this?

I looked at array_diff and array_intersect , but they compare values ​​with values, not the values ​​of one array with the keys of another.

+6
source share
4 answers

If I understand this correctly:

Returning a new array:

 $array_new = []; foreach($array_two as $key) { if(array_key_exists($key, $array_one)) { $array_new[$key] = $array_one[$key]; } } 

Removing from $ array_one:

 foreach($array_one as $key => $val) { if(array_search($key, $array_two) === false) { unset($array_one[$key]); } } 
+2
source

Starting with PHP 5.1, there is array_intersect_key ( manual ).

Just flip the second array from key => value to value => using array_flip() , and then compare the keys.

So, to compare OP arrays, this would do:

 $result = array_intersect_key( $array_one , array_flip( $array_two ) ); 

No need for any array loops.

+10
source

Tell me if this works:

 for($i=0;$i<count($array_two);$i++){ if($array_two[$i]==key($array_one)){ $array_final[$array_two[$i]]=$array_one[$array_two[$i]]; next($array_one); } } 
0
source

 <?php $array_one = array('colorZero'=>'black', 'colorOne'=>'red', 'colorTwo'=>'green', 'colorThree'=>'blue', 'colorFour'=>'purple', 'colorFive'=>'golden'); $array_two = array('colorOne', 'colorTwo', 'colorThree'); print_r(array_intersect_key($array_one, array_flip($array_two))); ?> 
0
source

Source: https://habr.com/ru/post/974267/


All Articles