1

In PHP, the string "1" equals the string "+1" unless you do a strict comparison (===).

echo ("1" == "+1") ? "equals" : "not equals"; // result: "equals" 

I'd prefer not to do a strict comparison, because the string "1" might be provided as an integer 1 in this case. I cannot do intval() to distinguish them because both return as 1, and I cannot do is_numeric() to distinguish them because both return true.

So, two questions please:

  1. Is there any way to differentiate between these other than to convert the input to strings via strval() and use strict comparison?

  2. Is this a bug or intended behavior in PHP? The reason doesn't seem mathematical ("2" does not equal "1+1" for instance, although "2" does equal "+2"). I'm curious as to the reasoning behind this.

9
  • 1
    Seems a bit contradictory what you want… :) You want loose comparison but not quite as loose as PHP defaults to…? Commented Feb 28, 2017 at 16:34
  • 1
    What about a pragmatic ((string)"1" === "+1") or ((string) intval("1") === "+1")? Commented Feb 28, 2017 at 16:34
  • 2
    "If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. " - PHP Docs Commented Feb 28, 2017 at 16:35
  • 1
    Mathematically, one and positive one are equivalent, that's basically what you're seeing. I'm not sure why you would prefer to not do a strict comparison here. Commented Feb 28, 2017 at 16:35
  • 1
    @nickb, thank you, that's what I was missing. I didn't see how "+1" could be considered a number unless it was mathematical (PHP treating it like "0+1"), but of course, it's positive one. I wish I had thought of that. Commented Feb 28, 2017 at 17:08

1 Answer 1

3

When using == instead of === a loose comparison is used.

This often leads to types using truthyness when comparing incomparable types

have a look a the manual here to see the table of comparison http://php.net/manual/en/types.comparisons.php

even though "+1" is not mentioned, it would be handled similarly to a '-1'

If you don't want this to happen, you do need to use ===

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.