简体   繁体   中英

Checking if array item is empty

I have two arrays:

$fields_data , which outputs:

Array ( [name] => [email] => [phone] => [message] => )

and $required_fields_array , which outputs:

Array ( [0] => name [1] => email [2] => message ) 

The values of $required_fields_array , are items in the $fields_data array .

I need to check each of the $required_fields_array against the $fields_data to check if the array item they correspond to is empty.

I have tried:

foreach( $required_fields_array as $key ) 
{                                       
    if ( isset($fields_data[$key]) === false && empty($fields_data[$key]) === true  )       
    {               
        print_r('empty');
    }           
}   

I can't see why the above isn't working.

Can anyone please point me in the right direction.

Try the following:

$fields_data = Array ( 'name' => '','email' => '','phone' => '','message' => '');
//Added extra element `asd` to show that `isset()` is not required
$required_fields_array = Array ('name','email',' message', 'asd');
foreach( $required_fields_array as $key ) 
{
    if(empty($fields_data[$key]))       
    {               
        print_r('empty');
    }           
}    

Remove the isset and === false etc. Because, empty() will do the isset() 's job too.

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