Array $ALLOWED_CALLS
contains a function name and required parameters. I'd like to filter $_REQUEST
array obtaining a $params
array with only required paramets in it. How to?
$call = 'translate';
$ALLOWED_CALLS = array(
'getLanguages' => array(),
'detect' => array('text'),
'translateFrom' => array('text', 'from', 'to'),
'translate' => array('text', 'to'),
);
$params = array(); // Should contain $_REQUEST['text'] and $_REQUEST['to']
I'd use array_intersect_key()
like so:
$params = array_intersect_key($_REQUEST, array_flip($ALLOWED_CALLS[$call]));
Thus, the whole thing:
$call = 'translate';
$ALLOWED_CALLS = array(
'getLanguages' => array(),
'detect' => array('text'),
'translateFrom' => array('text', 'from', 'to'),
'translate' => array('text', 'to'),
);
$params = array_intersect_key($_REQUEST, array_flip($ALLOWED_CALLS[$call]));
Have a look at array_intersect()
Something like:
$contains_required = true;
foreach( $ALLOWED_CALLS[$call] as $key => $value )
{
if(!in_array($value, $_REQUEST))
{
$contains_required = false;
}
}
function getParams ($call, $allowedCalls) {
// Return FALSE if the call was invalid
if (!isset($allowedCalls[$call])) return FALSE;
// Get allowed params from $_REQUEST into result array
$result = array();
foreach ($allowedCalls[$call] as $param) {
if (isset($_REQUEST[$param])) {
$result[$param] = $_REQUEST[$param];
}
}
// Return the result
return $result;
}
Returns the $params array, or FALSE
on failure.