检查PHP中至少一个字段是否为空

时间:2011-09-13 20:13:44

标签: php

我有以下字段:weight, size_1, size_2, size_3

如何检查以填充这些字段中的至少一个。

如果它低于最小值则应输出“错误,填写至少一个”

我可以用long if语句执行此操作,检查为空,但是它们是更好的方法吗?

字段来自表单提交,所以它看起来像这样:

$_POST['weight'];
$_POST['size_1'];
$_POST['size_2'];
$_POST['size_3'];

1 个答案:

答案 0 :(得分:5)

假设它们都在一个数组中:

function check_for_input($array){
     foreach($array as $value){
           if($value != "") return true;
     }
     return false;
}

像这样使用它:

if(check_for_input($_POST)){ /*...*/ }
else { die("Error, fill one at least"); }

使用过滤器更新:

假设它们都在一个数组中:

function check_for_input($array, $filter){
     foreach($array as $key=>$value){
           if($value != "" && in_array($key, $filter)){ 
                return true;
           }
     }
     return false;
}

像这样使用它:

$filter = array('weight', 'size_1', 'size_2', 'size_3', /*...*/);
if(check_for_input($_POST, $filter)){ /*...*/ }
else { die("Error, fill one at least"); }
相关问题