Home » Php » PHP string comparison with no quotes

PHP string comparison with no quotes

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&Answers:

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.

Answer:

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.

Answer:

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.

Answer:

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
}

Answer:

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.

Answer:

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 “===”