0

I have 2 arrays one is the collection of key and other with a collection of data ex.

$array1 = ['0'=>'A1','1'=>'A2','2'=>'A3']; 

and

$array2 = ['A1'=>'Data1','A2'=>'Data2','A3'=>'Data3','A4'=>'Data4','A5'=>'Data5']; 

I want data like this

$array = ['A1'=>'Data1','A2'=>'Data2','A3'=>'Data3']
abhayendra
  • 197
  • 6

3 Answers3

1

you can use array_filter for this:

$my_array = ['A1'=>'Data1','A2'=>'Data2','A3'=>'Data3','A4'=>'Data4','A5'=>'Data5'];
$allowed  = ['0'=>'A1','1'=>'A2','2'=>'A3']; 
$filtered = array_filter(
    $my_array,
    function ($key) use ($allowed) {
        return in_array($key, $allowed);
    },
    ARRAY_FILTER_USE_KEY
);

var_dump($filtered);

Output:

array(3) {
  ["A1"]=>
  string(5) "Data1"
  ["A2"]=>
  string(5) "Data2"
  ["A3"]=>
  string(5) "Data3"
}

Demo: https://3v4l.org/ZvkJb

Credit: PHP: How to use array_filter() to filter array keys?

catcon
  • 1,295
  • 1
  • 9
  • 18
  • You should update the code in your question to match your demo. As it is, what is in the question won't work. – Nick Oct 16 '19 at 05:53
0

You can also try this one to get the exact data of $array2 as you mentioned in the question.

$array1 = ['0'=>'A1','1'=>'A2','2'=>'A3']; 
$array2 = ['A1'=>'Data1','A2'=>'Data2','A3'=>'Data3','A4'=>'Data4','A5'=>'Data5']; 
$ans = [];
foreach($array1 as $value)
{
    if(isset($array2[$value]))
        $ans[$value] = $array2[$value];
}
print_r($ans);
Dhaval Purohit
  • 1,270
  • 10
  • 28
0

You can make $array1 a dic, then check if key in $array2 is set in the dic.

$array1 = array_flip($array1);
$result = [];
foreach($array2 as $k => $v){
    if(isset($array1[$k])){
        $result[$k] = $v;
    }
}
LF00
  • 27,015
  • 29
  • 156
  • 295