I have an array with 100 values(array1). I have another array with 8 values(array2). I want to take the values from array2 and use them as keys and extract the values in array1
Unfortunately, array_slice()
will disregard any association between the arrays based on keys/indexes. array_slice()
operates using offset
values; this is why it is the wrong tool for the job.
array_intersect_key()
is a suitable call to filter an array using another array's keys.
Code: (Demo)
for($char='A',$score=100; $score>0; ++$char,--$score){
$dr_img_scores1["IMG_$char"]=$score; // generate 100 unique elements
}
//var_export($dr_img_scores1); // uncomment to see what this looks like
// eight arbitrary elements to use as extraction keys on $array1
$dr_img_scores2=['IMG_CL'=>13,'IMG_Z'=>44,'IMG_BP'=>82,'IMG_L'=>50,
'IMG_CD'=>2,'IMG_X'=>91,'IMG_BM'=>7,'IMG_AV'=>0];
var_export(array_intersect_key($dr_img_scores1,$dr_img_scores2));
// notice that $dr_img_scores1's element order is preserved
Output:
array (
'IMG_L' => 89,
'IMG_X' => 77,
'IMG_Z' => 75,
'IMG_AV' => 53,
'IMG_BM' => 36,
'IMG_BP' => 33,
'IMG_CD' => 19,
'IMG_CL' => 11,
)
Note: If $dr_img_scores1
or $dr_img_scores2
are not in order, you can use ksort()
on them to synchronize their orders to permit an easy visual comparison of scores.