In PHP, boolean operators are frequently used for conditional checks. However, improper usage of boolean values may trigger the following warning:
PHP Notice: Use of undefined constant true/false - assumed 'true/false'
This warning indicates that an undefined constant was used where a boolean was expected. Next, we’ll analyze the cause and present common solutions.
The root cause is treating boolean values as strings or undefined constants. For example, the following code looks correct but will cause the warning:
$flag = true;
if($flag == true) { ... }
If PHP does not recognize true as a language keyword, it interprets it as a constant. If this constant is not defined, the warning occurs.
The simplest fix is to use PHP’s built-in true and false keywords and omit unnecessary comparisons:
$flag = true;
if($flag) { ... }
Since $flag is already boolean, == true is redundant.
If constants are needed to represent boolean values, define them explicitly:
define('MY_TRUE', true);
$flag = MY_TRUE;
if($flag == true) { ... }
This prevents PHP from interpreting MY_TRUE as an undefined identifier.
Using the strict equality operator not only checks value but also type:
$flag = true;
if($flag === true) { ... }
This approach avoids hidden bugs due to type coercion and is more robust.
When performing logical checks in PHP, proper boolean usage is essential. Keep in mind:
These practices effectively prevent common PHP warnings like “undefined constant true/false.”