Liam Schnell
Liam Schnell

Reputation: 482

PHP won't compare same string

If I display $d[0] it is [email protected] but it is refusing to accept the if...

$d = file("mails.txt");
if ($d[0] == "[email protected]") {
    echo "JOW!";
}
echo $d[0];

Any idea?

Upvotes: 4

Views: 1256

Answers (3)

Robert Hyatt
Robert Hyatt

Reputation: 791

I agree with Mike Lewis, using trim might fix why it was failing.

Also, in general, if you are having weird results in PHP when comparing strings, try '===' or strcomp to see that fixes the issue.

http://www.phpcatalyst.com/php-compare-strings.php

Upvotes: 4

Matthew
Matthew

Reputation: 48304

$d = file("mails.txt", FILE_IGNORE_NEW_LINES);
if ($d[0] == "[email protected]") {
    echo "JOW!";
}
echo $d[0];

Upvotes: 3

Mike Lewis
Mike Lewis

Reputation: 64177

Try calling the trim function on the $d[0], which will remove all new line characters at the beginning and end of the string.

        $d = file("mails.txt");
        if(trim($d[0])=="[email protected]"){
            echo "JOW!";
        }
        echo $d[0];

or not include any new lines at all:

        $d = file("mails.txt", FILE_IGNORE_NEW_LINES);
        if($d[0]=="[email protected]"){
            echo "JOW!";
        }
        echo $d[0];

Each line in the resulting array will include the line ending, unless FILE_IGNORE_NEW_LINES is used, so you still need to use rtrim() if you do not want the line ending present.

From: http://php.net/manual/en/function.file.php

Upvotes: 8

Related Questions