PHP filter_var_array() only check if one value is true?

I'm trying to check if many e-mail addresses are correct in order to send them.

The thing is, while I filter with filter_var_array() and FILTER_VALIDATE_EMAIL, if only one is correct among all the mails, it still proceeds.

Here is my code:

$test_email_friend = explode(",", $email_friend);
if ( !filter_var_array($test_email_friend, FILTER_VALIDATE_EMAIL)) {
    $errenvoi = "Please send only valid emails.";
} 
else {  
    //message, headers etc here
    if (mail($email_friend,$sujet,$message,$entete)){               
            $errenvoi = "Email sent !";
    } 
    else {
        $errenvoi = "Something very wrong happened, abandonship, I reapeat abandonship";            
    } 
}

For example: If the array contain "[email protected]" and "unvalidmess". It's sent anyway, because one of the value is correct.

How can I fix this?

Thanks a lot

728x90

1 Answers PHP filter_var_array() only check if one value is true?

If you read the docs, it says this function only returns false on failure (the function failed to execute). Otherwise, it returns an array. So the following for example:

$test = array('[email protected]', 'unvalidness');
var_dump(filter_var_array($test, FILTER_VALIDATE_EMAIL));

Will output:

array(2) {
  [0]=>
  string(13) "[email protected]"
  [1]=>
  bool(false)
}

You can alter your code to work by both checking for failure, and searching the returned array for any boolean false values:

$result = filter_var_array($test, FILTER_VALIDATE_EMAIL);
if (!$result || in_array(false, $result, true)) {
    echo 'failed or data not valid';
}

2 year ago