Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP string comparison with no quotes

Tags:

string

php

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?

like image 763
tronman Avatar asked May 04 '10 18:05

tronman


2 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.

like image 85
Will Vousden Avatar answered Sep 23 '22 18:09

Will Vousden


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.

like image 20
Greg Avatar answered Sep 24 '22 18:09

Greg