simplify this PHP code?
any ideas? in the second case $v is an array I could do is_array($v), but I'd have to repeat the if/else anyway
foreach(array('city', 'location') as $f) {
$ors[$f] = array();
if (!isset($_POST[$f])) continue;
$v = $_POST[$f];
if (isset($df[$f][$v])) {
array_push($ors[$f], $df[$f][$v]);
开发者_开发百科 }
else {
security_error();
}
}
foreach(array('age', 'sex') as $f) {
$ors[$f] = array();
if (!isset($_POST[$f])) continue;
foreach($_POST[$f] as $v) {
if (isset($df[$f][$v])) {
array_push($ors[$f], $df[$f][$v]);
}
else {
security_error();
}
}
}
Use ternary conditional operator for both loops:
$result = isset($df[$f][$v]) ? array_push($ors[$f], $df[$f][$v]) : security_error();
and/or for the function:
function pushIfSetOrSecurityError($source, $target, $key) {
$result = isset($source[$key]) ? array_push($target, $source[$key]) : security_error();
}
function pushIfSetOrSecurityError($source, $target, $key) {
if (isset($source[$key]))
array_push($target, $source[$key]);
else
security_error();
}
foreach(array('city', 'location') as $f) {
$ors[$f] = array();
if (isset($_POST[$f]))
pushIfSetOrSecurityError($df[$f], $ors[$f], $_POST[$f]);
}
foreach(array('age', 'sex') as $f) {
$ors[$f] = array();
if (isset($_POST[$f]))
foreach($_POST[$f] as $v)
pushIfSetOrSecurityError($df[$f], $ors[$f], $v);
}
精彩评论