How to differentiate "001" from "1" in PHP?

Asked

Viewed 80 times

1

If I compare 001 and 1 in PHP, it gives a result that the numbers are identical! Indeed it seems so! How do I differentiate 1 from 001, treat each one as if it were different?

  • even with ===?

  • Ivan, an important question, would be $foo = "001"; or would be $foo = 001;?

1 answer

8


Something tells me that there is already an answer to this but as the search returns nothing, it goes:

The comparison ends up being made by coercion and both are converted to number, so 1 is equal to 1. To ensure that the comparison is correct, you have to compare with the operator that does not coerce, and he is the === (identical). In fact almost always should use this operator and not the == (equal). This operator is problematic for not considering the type of data bringing unexpected results.

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Documentation.

  • Simple but interesting! Something I forgot to add the question! I’m making the comparison in the database! I use mysql for this. Trying to compare the filled variable with what is registered in the BD. I tried to use "===" but this operator is not accepted!

  • 1

    Although it is a different context from the original question, ask the question how it is doing and I try to adapt the answer. If you’re using it in SQL, that’s another thing, then the question isn’t even about PHP.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.