PHP: checking key value is not empty

13,659

Solution 1

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. E.g.

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

Solution 2

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

Solution 3

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]) != '')
Share:
13,659
elad.chen
Author by

elad.chen

Updated on June 04, 2022

Comments

  • elad.chen
    elad.chen almost 2 years

    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.