-1

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.

ccdavies
  • 1,576
  • 5
  • 19
  • 29
  • 2
    Remove the isset part. The fact that a variable is defined doesn't mean it is not empty – Rotimi Oct 12 '17 at 13:18
  • 3
    You're saying *if the value is not set __and__ it's empty*. You probably want an *or* there. And then you don't need the `isset` at all. – deceze Oct 12 '17 at 13:19
  • Remove === false === true from both isset and empty, bcoz if its either empty or not set your condition will return true and it goes in if – shashi Oct 12 '17 at 13:20
  • Keep it as if ( isset($fields_data[$key]) && !empty($fields_data[$key]) ) , your code if fine otherwise – shashi Oct 12 '17 at 13:22
  • @shashi [Why check both isset() and !empty()](https://stackoverflow.com/q/4559925/476) – deceze Oct 12 '17 at 13:23

1 Answers1

1

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.

mega6382
  • 9,211
  • 17
  • 48
  • 69