Question

For example:

$searchParameters = array(
    'parameter1' => 'value1',
    'parameter2' => 'value2',
    'parameter3' => 'value3',
);

$allowedParamters = array('parameter1','parameter2');

What's the best way to get $searchParameters containing only the allowed pairs?

Was it helpful?

Solution

Use array_intersect_key() :

$searchParameters = array(
    'parameter1' => 'value1',
    'parameter2' => 'value2',
    'parameter3' => 'value3',
);
$allowedParamters = array('parameter1','parameter2');

$result = array_intersect_key($searchParameters, array_flip($allowedParamters));

OTHER TIPS

foreach($searchParameters as $key => $value) {
    if(!array_key_exists($key, $allowedParamters)) {
        unset($searchParameters[$key];
    }
}

This will delete the not-allowed keys and their value.

foreach($searchParameters as $key=>$value){
    if(in_array($key,$allowedParamters)){
        $trueResult[$key] = $value;
    }
}
print_r($trueResult);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top