Iterate through an array, looking for keys that match the values of another array
This is probably a si开发者_如何学运维mple question...
I have a multidimensional array called $form. I need to iterate through the array, looking for specific keys that match another array values and then perform an action in those keys.
$a = 'theme_select';
$b = 'timezone';
$c = 'contact';
$d = 'something_else';
$arr = array();
$arr = ($a, $b, $c, $d);
foreach($form as $form_key=>$form_val){
foreach($arr as $include) {
if ($form_key == $include) {
//some action
}
}
}
Is this the best way to accomplish this? The reason I'm asking is that $form can be quite big and I fear that page loading can become quite slow.
Have a look at the array_intersect_key() function
$a = 'theme_select';
$b = 'timezone';
$c = 'contact';
$d = 'something_else';
$arr = array_fill_keys(array($a, $b, $c, $d),1);
$matchingKeys = array_intersect_keys($form,$arr);
foreach($matchingKeys as $key => $value) {
...
}
精彩评论