使用array_merge创建函数

时间:2012-05-05 05:28:44

标签: php arrays function array-merge

不检查是否存在上述字段。两个版本

第一版:

$error = array();
$field_sets = array('username','password','fullname','repeatpass','email');
foreach($field_sets as $fieldname){
    if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) {
        $error[] = $fieldname;
    }
}

第二版:

(in the includes file)
function check_required_fields ($required_array){
    $error = array();
    foreach($required_array as $fieldname){
        if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) { 
            $error[] = $fieldname;
        }
    }
    return $error;
}

In the Source File:
$error = array();
$required_field = array('username','password','fullname','repeatpass','email');
$error = array_merge($error , check_required_fields($required_field , $_POST));

1 个答案:

答案 0 :(得分:0)

我发现了问题。我不小心把&&放在了逻辑中。它应该是||而不是&&

          if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) || $_POST[$fieldname] != 0))