Travis Emery
Travis Emery

Reputation: 89

string comparison in php

I am trying to compare two strings I get from a password form in HTML.

They are being stored in variables from $_POST. I print them out and they look the same, but the code below will never evaluate to true, only false. Why does that happen?

//Verify the passwords match
if( ($passwd != $pass_confirm) && ($new_email != $email_confirm) ){
    echo "Email and/or password do not match";
    return FALSE;
}

I appreciate any help.

Upvotes: 0

Views: 241

Answers (2)

Oleg
Oleg

Reputation: 9359

If you print them out and they look the same, you might have a trailing newline character problem. Perhaps you could try trimming the strings before comparison? Doing a var_dump might help to pinpoint the problem because it shows the length of the string.

Also, I would suggest the following check (note the || and strict comparison operators):

if ($passwd !== $pass_confirm || $new_email !== $email_confirm) {
    echo "Email and/or password do not match";
    return false;
}

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

For your code to show the error message, both the email and password must be wrong.

Try using || instead of &&, so the error is shown when just one of them is wrong.

Upvotes: 7

Related Questions