Нет необходимости создавать собственный массив входных переменных, так как у вас уже есть $ _POST:
$_POST = array_map('myescape_function', $_POST);
foreach($fields_to_validate_arr as $v){
if(empty($_POST[$v]) || $_POST[$v] == 'undefined'){
//increment the error message with a custom error message.
$error_message .= "->" . ucwords(str_replace('_',' ',$v)) . "<br />";
}
}
Поскольку значения не хранятся в отдельных переменных, проблема печати имени переменной, а не ее значения, устраняется.
Если вы хотите стать действительно модным, вы можете добавить поддержку пользовательских валидаторов:
function inputExists($name, &$source) {
return !empty($source[$name]) && 'undefined' != $source[$name];
}
function inputIsNumeric($name, &$source) {
return inputExists($name, $source) && is_numeric($source[$name]);
}
// checks for U.S. phone numbers only
function inputIsPhone($name, &$source) {
if (inputExists($name, $source)) {
// strip whatever non-numeric
$value = preg_replace('/[-.,() \t]+/', '', $source[$name]);
return preg_match('^(1?[2-9]\d{2})?[2-9]\d{6}$', $value);
}
return False;
}
function inputMatchesRE($name, &$source, $RE) {
return inputExists($name, $source) && preg_match($RE, $source[$name]);
}
function nameAndValidator($name, $validator) {
if (function_exists($validator)) {
return array('name' => $name, 'validator' => $validator, 'data' => '');
} elseif (is_numeric($name)) {
// if index is numeric, assume $validator actually holds the name
return array('name' => $validator, 'validator' => 'inputExists', 'data' => '');
} else {
return array('name' => $name, 'validator' => 'inputMatchesRE', 'data' => $validator);
}
}
$fields_to_validate_arr = array('name', 'street' => '/^\d+ +[a-z ]+(ave|st|wy|way|ln|lp|blvd)$/i', 'age'=> 'inputIsNumeric', 'phone' => 'inputIsPhone');
$_POST = array_map('myescape_function', $_POST);
foreach($fields_to_validate_arr as $name => $validator){
list($name, $validator, $data) = nameAndValidator($name, $validator);
if(! call_user_func($validator, $name, $_POST, $data)){
//increment the error message with a custom error message.
$error_message .= "->" . ucwords(str_replace('_',' ',$v)) . "<br />";
}
}