tronman
tronman

Reputation: 10115

PHP string comparison with no quotes

From what I know about PHP, the following syntax is not legal:

if ($s == Yes)

It should instead be written as:

if ($s == 'Yes')

However, the first example is working just fine. Anyone know why?

Upvotes: 7

Views: 804

Answers (6)

Cristian Rodriguez
Cristian Rodriguez

Reputation: 629

PHP converts Yes to 'Yes' internally when constant Yes is found not to be defined.

Btw.. If what you want is comparing if $s has "Yes" as value an is a string then you have to

a) use strcmp or b) use the identity operator "==="

Upvotes: 0

Harold1983-
Harold1983-

Reputation: 3369

You need to have both error_reporting showing notices, and display_errors set on.

error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', '1');

if ($s == Yes) {
  // foo
}

Upvotes: 1

dmertl
dmertl

Reputation: 825

In PHP that Yes would be treated as a constant. If the constant is undefined it will assume you meant the string 'Yes'. It should generate a notification if you have them turned on.

Upvotes: 0

Your Common Sense
Your Common Sense

Reputation: 157828

The first one is not a string.

And it is not works fine:

error_reporting(E_ALL);
if ($s == Yes) {}

It's a legacy from the times when PHP were just a "Pretty home page" form interpreter and strongly discouraged nowadays.

Upvotes: 1

Greg
Greg

Reputation: 12837

In short, PHP is acting as if the quotes were there.

If PHP doesn't recognize something as a reserved token, it treats it as a string literal.

The error log will show a warning about this.

Upvotes: 8

Will Vousden
Will Vousden

Reputation: 33348

Ordinarily, it would be interpreted as a constant, but if PHP can't find a constant by that name, then it assumes it to be a string literal despite the lack of quotes. This will generate an E_NOTICE message (which may not be visible, depending on your error reporting level); something like:

Notice: Use of undefined constant Yes - assumed 'Yes' in script.php on line 3

Basically, PHP is just overly lenient.

Upvotes: 14

Related Questions