简体   繁体   English

PHP:检查键值不为空

[英]PHP: checking key value is not empty

I wrote a small function to check the required fields of a form, are not empty. 我写了一个小函数来检查表单的必填字段,不是空的。 The function accepts two arguments, 1st is an array with all values from $_POST superglobal. 该函数接受两个参数,1st是一个包含$ _POST superglobal的所有值的数组。 2nd is the required fields array which I populate. 第二个是我填充的必填字段数组。

Have a look: 看一看:

public $errors = array();

public function validate_fields($fields_array, $required_fields) 
{
    foreach ($required_fields as $key => $value)
    {
        if (array_key_exists($key, $fields_array)) 
        {
            # If key exists in $fields_array
            # check that the key value inside $fields_array is set & isn't empty
            # if it's empty, populate with an error
            if(empty($fields_array[$key][$value]))
            {
                $this->errors[] = "{$key} is empty but in fields_array";
            }
        }
        else 
        {
            # Key does not exists in $fields_array
            # Did someone temper with my html ?
            $this->errors[] = "{$key} is not in fields_array";
        }
    }
    return (empty($this->errors)) ? true : false;
}     

The issue I'm having seems to be related to "if(empty($fields_array[$key][$value]))" statement. 我遇到的问题似乎与“if(empty($ fields_array [$ key] [$ value]))”语句有关。 my goal is to check that $fields_array key value is not empty based on $required_fields key. 我的目标是根据$ required_fields键检查$ fields_array键值是否为空。 I'm sure the statement I'm using is off. 我确定我正在使用的声明已关闭。 If you see anything that you think can be written better, please let me know, as I am new to php. 如果你看到任何你认为可以写得更好的东西,请告诉我,因为我是php新手。 Appreciate the help. 感谢帮助。

I think what you're trying to do is: 我想你要做的是:

if(empty($fields_array[$key])) {
    //this means value does not exist or is FALSE
}

If you also want to check for empty-strings or white-space only, then you need something more than just empty. 如果您还想仅检查空字符串或空白区域,那么您需要的不仅仅是空的。 Eg 例如

if(empty($fields_array[$key]) || !trim($fields_array[$key]))         {
    //this means key exists but value is null or empty string or whitespace only
}

Do note that the above answers will only work for indexed arrays in >PHP 5.4. 请注意,上述答案仅适用于> PHP 5.4中的索引数组。 If you have an associative array you have to use isset instead of empty: 如果你有一个关联数组,你必须使用isset而不是empty:

if(isset($fields_array[$key]) && trim($fields_array[$key]) != '')

See http://nl3.php.net/manual/en/function.empty.php , example #2 http://nl3.php.net/manual/en/function.empty.php ,例子#2

You don't need to select the value as an index just key. 您不需要选择值作为索引只是键。 Where $fields_array[$key] = $value; $ fields_array [$ key] = $ value;

if(empty($fields_array[$key]) && trim($fields_array[$key]) != '')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM