Evolution Note: This sketch was drawn in May 2018 and reviewed in October 2026. It serves as a visual reference for dynamic type juggling in PHP. While my daily work now centers on Python and distributed backends, visual diagrams remain handy reference artifacts. For current engineering writings, visit the homepage.

PHP booleans

Understanding Loose Type Coercion in PHP

Dynamically typed runtimes perform automatic type conversion when evaluating condition expressions. When a variable passes into an if ($value) statement, PHP coerces the variable into a boolean representation according to language conversion rules.

While converting integers like 1 or strings with characters feels intuitive, several non-boolean values evaluate to false in subtle ways that cause bugs in web applications.

Values That Evaluate to False

PHP treats several values as falsy during conditional checks:

  • The empty string "" as well as the string "0".
  • Empty arrays ([]) and uninitialized variables (null).
  • The integer 0 and floating point equivalent 0.0.
  • SimpleXML objects created from empty tags.

The string "0" is a frequent source of confusion for engineers transitioning from other languages. While JavaScript and Python treat any non-empty string as truthy, PHP historically coerced "0" to false so that web forms submitting numeric inputs could be evaluated with simple conditional expressions.

Why Loose Equality Breaks API Handlers

Consider an API endpoint that parses an incoming JSON payload containing an identifier or pagination parameter:

$offset = $request->get('offset'); // contains "0"

if (!$offset) {
    // This branch executes even though the client explicitly supplied "0"
    $offset = 10;
}

Because "0" coerces to false, the fallback triggers unexpectedly, altering the client query.

A similar problem appears when using strpos() to locate substrings:

$position = strpos("production", "prod"); // returns integer 0

if ($position == false) {
    // Executes because 0 == false evaluates to true under loose comparison
    echo "Substring missing";
}

Safe Patterns: Strict Equality and Explicit Checks

To avoid unexpected coercion behaviors in production services, standard engineering practices favor explicit checks:

  1. Use identity operators (=== and !==) to ensure both type and value match before proceeding.
  2. Use dedicated helper functions such as strlen($val) > 0 or isset() when verifying form fields.
  3. For numeric parameters, use is_numeric() or explicit (int) casts so that the digit 0 remains valid data rather than a falsy condition.