View Full Version : 2 variables with the same string doesn't match.

08-30-2007, 01:18 PM
I've transfered a bunch of names from a txt file into an array.
Now i need to compare it against a string i have.
When the strings are the same, for some reason it returns 'false' when i compare it.
any idea what's the problem? the names are the same but i don't know
why's the result is false....

08-30-2007, 01:36 PM
Please give some code/test-data.

08-30-2007, 01:40 PM
Sounds like you are using the "==" operator when you are comparing strings...and unfortunately..."==" operator does not always evaluate expressions on strings correctly.

you should make use of the "strcmp (http://www.php.net/strcmp)" function when you are trying to comapre strings.

here is an example

$str1 = "hello world";
$str2 = "Hello World";

if( strcmp( $str1, $str2 ) == 0 ) {
echo "Strings are equal";
} else{
echo "Strings are not equal";

Note: strcmp is case sensitive...so, in the above example, you should expect "Strings are not equal"...if you want to use a case-insensitive alternative to strcmp, please use strncasecmp (http://www.php.net/manual/en/function.strncasecmp.php)


08-30-2007, 01:44 PM
$ourFileName = "file.txt";

$fh = fopen($ourFileName, 'r+') or die("Can't open file");

$a = 0;
while (!feof($fh))
$names[$a] = fgets($fh);

/// for example you're looking for the username 'asdf'///
$b = 0;
$as = 'asdf';
foreach ($names as $nnn)
if ($names[$b] == $as)

echo "good";
echo $names[$b];

when i add "echo $names[$b];" to the loop
it prints everything as it is in the txt file
but for some reason it doesn't execute the code inside the if statement
when the array string is the same as the string i am trying to compare against.

edit: thank you ess, i'll try if it works when i am at home.

09-02-2007, 04:41 PM
The string returned by fgets (http://de2.php.net/manual/en/function.fgets.php) may include a newline at the end. Use rtrim (http://de2.php.net/manual/en/function.rtrim.php) on the returned value before you stuff it into the array.


Edit: And contrary to a comment made above the Equality Operator == does always evaluate expressions on strings correctly (according to the rules of the language).