PHP变量及其检查null与某些规则

时间:2014-05-30 04:51:32

标签: php variables refactoring

我想要一些关于php的提示

这是我的变量

$error;
$a=$_POST["sdf"];
$b=$_POST["dsf"];
$c=$_POST["ssdfsdfdf"];
$d=$_POST["ssdfsddf"];
$e=$_POST["sdfsdfdf"];
$f=$_POST["sfsdfsdf"];
$g=$_POST["sdsdff"];
$g=$_POST["sdsdfsdff"];

我想检查这些变量是否为空,并且显示这样的消息

if(empty($a)){
$error.="Hey you missed the $a "; // $a value
}

现在我必须重复所有这些代码...

想象一下,我有超过40个变量,我可以得到一些提示来缩短代码

我尝试过switch语句,但它没有工作..我想显示任何变量的所有错误信息都丢失..​​.

此致

3 个答案:

答案 0 :(得分:2)

$required = ["sdf", "dsf", "ssdfsdfdf"]; //etc. etc.
$arr = [];
//Loop through and santize input. 
foreach($_POST as $key => $value)
{
    //sanitize input here

    //store in array
    $arr[$key] = $value; 
}

//check empty
foreach($arr as $key => $value)
{
    if(in_array($key, $required)
    {
       if(empty($value))
       { 
           throw new Exception("One of the required attributes is empty"); 
       }
    }
}

答案 1 :(得分:1)

不要分配给变量。您可以直接处理POST数组

foreach($_POST as $value) {
if(is_array($value)) {
    foreach($value as $val) {
       if(empty($val)){
          $error.="Hey you missed the $val "; // $a value
       }
    }
} else {
     if(empty($value)){
          $error.="Hey you missed the $value "; // $a value
     }
}
}

答案 2 :(得分:1)

如果您想检查页面中的所有POST变量,请尝试使用foreach,如下所示

foreach($_POST as $key=>$values)
{
if($values == "")
echo "Hey you missed out ".$key;
}

Note :在密钥(POST变量)中使用合理的命名,以便有助于显示消息