1

The following appears to work, yet I really don't think it should:

if ("'True','False'" == 0) { echo 'Hello, World.'; } 

Is it grepping the last False out of the string, and if so why, and how do you stop it?

4 Answers 4

3

This is due to loose typing. When you compare a string to a number, PHP has to cast one to the other's type. In this case, the string, when casted to an integer, is worth 0, your condition being True.

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

Comments

1

Any string evaluates to 0 when being compared against a number (unless it's a stringed number such as "5" or "4string"). That's why it'll always evaluate to 0.

See the Type Comparison Table

Comments

1

What's really happening is that PHP is trying to do an implicit type conversion, and for one reason or another it's deciding that string when converted to an integer looks like 0. You can prove this to yourself by doing:

echo ((int) "'True','False'"); 

If you want to do a type-checked comparison you should use the triple equals (===):

if("'True','False'" === 0) 

...which will most certainly evaluate to false.

Comments

1

No; it's converting the string "'True','False'" to a number — and that number is 0. 0 == 0 is true. You can solve it by using !"'True','False'" if I understand your intent correctly, or by using strict equality, ===, which you should generally use.

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.