-3

in my code I wanted to compare two strings and first I did it with === but later i tryed strcmp(). When i write:

echo strcmp("test","test");

the result was 0. I also tried it with ===

echo ($subject === $empty)

there i used my actual strings i wanted to compare.

However. Why is the string comparde method only True if the zweo string arent the same. Because:

echo strcmp("test","tedddst");

delivers True.

  • 1
    You need to understand what PHP equates Boolean true to. `true == 1 && true == 11`. Do NOT use bools to evaluate the response from this function. Test equality with `=== 0`. – ficuscr Jun 27 '18 at 18:03

3 Answers3

2

strcmp doesn't return a boolean true/false, it returns an int. From the strcmp documentation:

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Richard
  • 528
  • 2
  • 15
0
strcmp 

According to the documentation is binary safe string comparison.

int strcmp ( string $str1 , string $str2 );

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

=== will return true or false

Jyothish V
  • 66
  • 9
0

strcmp function compares given strings and returns a number, not a boolean.

In your last example, the returned value is different from 0, which is True if you parse it in boolean type.

Back to your first problem, string comparison. You can check if strcmp(str1, str2) is equal to 0, not a boolean value.

You can check the return value section in referenced URL for more information.

ngdangdat
  • 1
  • 1