Diljit PR
Diljit PR

Reputation: 311

Strings Same but evaluates to false on equality?

I am trying to read a file in my localhost and compare the equivalent string with another string. The contents of the strings are exactly the same and I have done the following:

$homepage = file_get_contents('./output.txt');
$input="some string"

strcmp($input,$homepage) //this statement evaluates to -1..

Where am i going wrong..? How do i cross-check whether the string read from the file is exactly same as the string to be compared..?

Here's a screen-shot with two strings echoed..

enter image description here

Upvotes: 0

Views: 76

Answers (2)

kguest
kguest

Reputation: 3844

There may be a newline character present in the string that you've read from the file. The best thing to do when taking in input from an external source is to trim out trailing and leading spaces (and also filter/validate as well, but that's another issue).

e.g.

$homepage = trim(file_get_contents('./output.txt'));
$input="some string";

As a further example:

kguest@radagast:~$ php -a
Interactive mode enabled

php > $f = "  foo \n";
php > $b = "foo";
php > var_dump($f === $b);
bool(false)
php > var_dump(trim($f) === $b);
bool(true)
php > var_dump(strcmp(trim($f), $b));
int(0)
php > 

Upvotes: 0

hek2mgl
hek2mgl

Reputation: 157967

Try this:

strcmp($input, trim($homepage));

I'm using trim() to remove leading or trailing whitespace from $homepage. As I've told in comments, I guess that there is a newline at the end of $homepage.

Upvotes: 2

Related Questions