0

There are lots of examples of false positives when using == to compare two strings in PHP.

For example, '1' == '1.0' is true.

However, are there any false negatives? Is there some string $a such that $a == $a is false due to type juggling?

Nick Frost
  • 490
  • 2
  • 12
  • 1
    if you want avoid some false positive use strict compare '1' === '1.0' so you compare type and value and not only value – ScaisEdge Feb 26 '17 at 20:45
  • Or you can use `strcmp()` and `strcasecmp()` to compare string. – frz3993 Feb 26 '17 at 20:47
  • Is that a typo? Or are you really looking for a string that is not equal to itself? Because no, there is no situation in PHP where `$a == $a` would ever evaluate to `false`. – AmericanUmlaut Feb 26 '17 at 20:50
  • http://php.net/manual/ru/language.operators.comparison.php – bxN5 Feb 26 '17 at 21:27
  • I'm sorry, but a string comparison from "1.0" == "1" is not true. If you want to compare the values of the strings, you need to convert them to numeric values before or during the test: if (floatval('1') == floatval('1.0')) would be true, as it is comparing the correct types. Read about type juggling: http://php.net/manual/en/language.types.type-juggling.php – R. Smith Feb 26 '17 at 21:31
  • PHP will still type juggle even if both inputs are already strings. `var_dump('1.0' == '1')` => `bool(true)`, but `var_dump('1.0' === '1')` => `bool(false)` – Nick Frost Feb 26 '17 at 21:36

1 Answers1

1

No, php will not provide false negatives. php will create false positives via type juggling as a feature (it tries to help).

Related questions:

php string comparison unexpected type juggling

Type casting and Comparison with Loose Operator "=="

Community
  • 1
  • 1
mickmackusa
  • 43,625
  • 12
  • 83
  • 136