0

I made a function to validate the e-mail address to vaidate and check if they are matched or not.

But it doesn't seem to work because when I var_dump().

I got the null value such as: NULL string(13) 123@gmail.com. Could you give me some advice to fix this? I'm completely stuck.

function email_validate_n_match($value)
{

    if( $value == '') return;
    if( preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $value) ) {

        static $count = 0;

        if($count == 0) {
            $value1 = $value;
        } else if($count == 1) {
            $value2 = $value;
        }

        var_dump($value2);

        // if ($value1 == $value2) {
            //  return;
        // }else{
            //  $this->clear = false;
            //  return $this->tag_st . 'Doesn't match.' . $this->tag_ed;
        // }

        $count++;

        return;

    } else {

        $this->clear = false;

        return $this->tag_st . 'Put the correct email address.' . $this->tag_ed;
    }
}

EDIT:

Thanks for the answers.

When I put this

static $count = 0;

if($count == 0) {
    $value1 = $value;
    echo '0';
} else if($count == 1) {
    $value2 = $value;
    echo '1';
}

it outputs 01. On the other hand,

If I remove static, I get 00.

so I think this $count is working, but I'm still confused why I got NULL result above.

Kevin
  • 41,694
  • 12
  • 53
  • 70
Toshi
  • 6,012
  • 8
  • 35
  • 58
  • 4
    Have you considered validating emails with [filter_var](http://php.net/manual/en/filter.examples.validation.php)? – Dave Chen Aug 01 '14 at 01:51

2 Answers2

1

You set $count = 0, then set $value1 = $value, but never set $value2 to anything because $count is not equal to 1, so $value2 is null, which is why var_dump gives you null. You then increase count to 1 using $count++, but the next time it runs, count will be set back to 0.

piergiaj
  • 629
  • 3
  • 9
  • @piergialj: Thanks. To fix this, should I use global variable or any other idea? I'm new for using php. – Toshi Aug 01 '14 at 01:59
  • I'm not sure why you have the $count variable to begin with. Do you even need it? What are you trying to do with $count? – piergiaj Aug 01 '14 at 02:01
  • I'm trying to count how many times the function is called here. I simply want to make some function which can get two email addresses from the forms, and check them if their values are email address plus if they are matched or not at the same time. – Toshi Aug 01 '14 at 02:05
1

why taking the time to validate the email while PHP has a function to do that for you? for example:

if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
 echo "valid";
}else{
 echo "not Valid";
}

here you can find more.

PHP Filters

Kosh
  • 6,140
  • 3
  • 36
  • 67