简体   繁体   中英

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. 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. my goal is to check that $fields_array key value is not empty based on $required_fields key. 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. 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. If you have an associative array you have to use isset instead of empty:

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

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

You don't need to select the value as an index just key. Where $fields_array[$key] = $value;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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