Php – Filtering email addresses in an array -php

array-filterPHP

I have a php array containing email addresses as array(email_address1 => name1, email2 => name2) format.

I need to check that emails are valid and I can foreach and

foreach($arr as $email => $name) { 
   $new = array();
   if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
   $new[$email] = $name;
  }
return $new;
}

Can I achieve the above using array_filter? what would be the syntax??

array_filter($emails_arr, 'filter_var') ?? how about FILTER_VALIDATE_EMAIL parameter?

thanks.

Best Answer

Since you are using the eMails as array keys, you cannot use array_filter and filter_var together directly. You'd have to write a callback function that you can pass to array_filter that operates on the array keys instead of the values; in which case you can just as well stick with your foreach solution.

Note that me@the.foo and mary@had.a.little.la.mb are both considered valid by filter_var, because it will only test syntax and not semantics.