Using empty() can sometimes be problematic, as values of 0, "0", "" and boolean false are all considered "empty", so it can be a problem in this case if 0 is a valid entry.
$REQUEST can be a little iffy in that how it handles things if there is, for example, both a $GET['key'] and a $POST['key'] is dependent on your local PHP configuration as to which value is used for $REQUEST['key'].
Otherwise, the basic premise is OK, though I personally prefer to avoid variable variables in that I just find them a bit harder to read. Anyway, if you go with that approach, you could get notice-level warnings thrown if neither the $POST nor $GET value is set.
So, you could do:
$keys = array('age', 'gender', 'etc')
foreach($keys as $key)
{
$$key = (isset($_GET[$key]) && trim($_GET[$key]) !== '') ? trim($_GET[$key]) :
(isset($_POST[$key]) && trim($_POST[$key] !== '') ? trim($_POST[$key]) : null;
}
(Hope there aren't too many typos in there. 😉 )
You could likewise use the array and variable variables with my function:
function getInput($key)
{
if(isset($_GET[$key]) && trim($_GET[$key]) !== '')
{
return(trim($_GET[$key]));
}
elseif(isset($_POST[$key]) && trim($_POST[$key]) !== '')
{
return(trim($_POST[$key]));
}
return null;
}
$keys = array('age', 'gender', 'etc.');
foreach($keys as $key)
{
$$key = getInput($key);
}
Remember, shorter is not always better (though it might be). Go for correctness, efficiency, and maintainability (including avoiding repetitious code). If that also results in shorter code, that's all to the better but not a requirement.