Current Location: Home> Latest Articles> PHP Boolean Operation Error Fix: Correct Usage of Undefined Constant true/false

PHP Boolean Operation Error Fix: Correct Usage of Undefined Constant true/false

gitbox 2025-06-06

1. Problem Description

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.

2. Cause of the Warning

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.

3. Correct Solutions

3.1 Use Built-in Boolean Values

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.

3.2 Define Boolean Constants

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.

3.3 Use Strict Comparison Operator (===)

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.

4. Summary

When performing logical checks in PHP, proper boolean usage is essential. Keep in mind:

  • Use true and false directly to avoid typos or undefined constants
  • Define boolean constants with define() if necessary
  • Prefer strict comparison (===) for safer and clearer code

These practices effectively prevent common PHP warnings like “undefined constant true/false.”