Jump to content

Email check function


phpjon420

Recommended Posts

I'm having a problem with a function that I wrote.

I want it to...

-> Take an email address from a form

-> Check to see if the email is valid

-> If valid, add it to an array $valid

-> If invalid, add it to an array $invalid

 

It's not doing that. Here is the file....

 

<?php

   extract($_GET, EXTR_OVERWRITE);

function email_check($email,$valid,$invalid) {
   $boo = preg_match("/^[^@]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$/", $email);
   if($boo == '1') {
      array_push($valid, $email);
   } else {
      array_push($invalid, $email);
   }
}

$valid = array();
$invalid = array();

email_check($email1,$valid,$invalid);
email_check($email2,$valid,$invalid);
email_check($email3,$valid,$invalid);

print_r($valid);

?>

 

Could anyone offer any help?

Link to comment
https://forums.phpfreaks.com/topic/241080-email-check-function/
Share on other sites

You want to pass by reference in your function

 

function email_check($email,&$valid,&$invalid)

 

You may also want to make sure its an array with either

 

function email_check($email, array &$valid, array &$invalid)

 

or

 

function email_check($email,&$valid,&$invalid) {
$boo = preg_match("/^[^@]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$/", $email);
if( $boo == TRUE ) {
	if ( is_array($valid) ) array_push($valid, $email); else $valid = $email;
} else {
	if ( is_array($invalid) ) array_push($invalid, $email); else $invalid = $email;
}
}

 

BTW - checking if $boo = '1' isn't a good idea. Quoting the '1' makes it a string, and forces PHP to typecast it as boolean/int when it tries to compare. Instead, use the constant TRUE or integer 1 (without quotes)

Make sure your input is correct.

 

<?php

function email_check($email,&$valid,&$invalid) {
$boo = preg_match("/^[^@]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$/", $email);
if( $boo == TRUE ) {
	if ( is_array($valid) ) array_push($valid, $email); else $valid = $email;
} else {
	if ( is_array($invalid) ) array_push($invalid, $email); else $invalid = $email;
}
}

$emails = array(
'[email protected]',
'[email protected]',
'[email protected]',
'notvalid'
);

$v = array(); $i = array();

foreach( $emails as $email )
email_check( $email, $v, $i );

print_r( $v );
print_r( $i );


?>

 

outputs

 

Array
(
    [0] => [email protected]
    [1] => [email protected]
    [2] => [email protected]
)
Array
(
    [0] => notvalid
)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.