Eduardo Arsand

Understanding Common Edge Cases in PHP and JavaScript

133

An edge case is an input or state near the boundary of what code expects. It can be valid but uncommon, malformed, or simply overlooked. It is not automatically a bug; the code still needs a deliberate behavior for it.

Common Edge Cases in PHP

1. Type Juggling and Loose Comparisons

Loose comparisons can coerce operands, and the behavior changed in PHP 8.0:

<?php
    var_dump("0" == false);     // true
    var_dump("123abc" == 123);  // true before PHP 8.0; false since PHP 8.0
?>

That difference can lead to unexpected branches. Use === when the type must match. declare(strict_types=1) affects scalar-typed function calls made from that file; it does not change the behavior of ==. See the PHP comparison rules and strict type declarations.

2. null, Empty Strings, "0", and false

<?php
    var_dump(empty("0")); // true
?>

empty() also treats 0, false, null, "", an empty array, and an undefined value as empty. If "0" is valid data for a field, check for the specific missing or empty values you intend to reject. See the empty() documentation.

3. Array Key Conversion

<?php
    $array = [
        "1" => "a",
        1 => "b"
    ];
    print_r($array); // one key: 1 => "b"
?>

PHP converts valid decimal integer string keys such as "1" to integers. When two entries resolve to the same key, the later value replaces the earlier one. A string such as "01" remains a string key. See PHP array key conversion.

4. Floating-Point Precision

<?php
    var_dump(0.1 + 0.2 === 0.3); // false
?>

Binary floating-point values have limited precision, so avoid relying on exact equality for calculated decimal amounts. For currency, integer minor units or decimal arithmetic are usually a better fit. PHP's floating-point documentation describes the rounding limits; BCMath provides arbitrary-precision decimal operations.

5. Missing Array Keys

<?php
    echo $_GET['id']; // E_WARNING since PHP 8.0; E_NOTICE in earlier versions
?>

The null coalescing operator supplies a default when a key is missing or its value is null:

<?php
    $id = $_GET['id'] ?? null;
?>

If the distinction between a missing key and a key whose value is null matters, check key existence explicitly. See the PHP array documentation.

6. String Length and UTF-8

<?php
    strlen("á");                 // 2 bytes when the source is UTF-8
    mb_strlen("á", "UTF-8");     // 1 code point for precomposed á
?>

strlen() counts bytes. mb_strlen() counts characters according to the encoding you pass (or the configured default). Choose the unit your code needs: bytes, code points, or grapheme clusters. See the strlen() documentation and PHP string encoding notes.

Common Edge Cases in JavaScript

1. Truthy and Falsy Values

Boolean([])        // true
Boolean({})        // true
Boolean("")        // false
Boolean("0")       // true
Boolean(0)         // false
Boolean(null)      // false
Boolean(undefined) // false

Arrays and objects are truthy, even when empty. If an empty array or object means “no data” in your code, check its contents explicitly instead of relying on truthiness.

2. == vs. ===

"0" == 0      // true
"" == 0       // true
false == []   // true

== converts values in some comparisons. Prefer === when the types should match; use coercive equality only when that conversion is intentional. See the ECMAScript equality algorithm and MDN's equality operator reference.

3. NaN

NaN === NaN // false

Use Number.isNaN(value) when you need to check whether a value is the numeric NaN. Unlike the global isNaN(), it does not coerce its argument. See the ECMAScript specification for Number.isNaN and MDN's reference.

4. Floating-Point Precision

0.1 + 0.2 === 0.3 // false

As in PHP, do not assume calculated decimal values can be compared exactly. Use integer units or an appropriate decimal representation when exact amounts matter.

5. Asynchronous Timing

let result;

fetch(url).then(response => {
    result = response;
});

console.log(result); // undefined: the callback runs later

If later code needs the response, wait for the promise with await inside an async function, or continue the work in .then(). Reading the variable immediately after starting the request happens before the callback assigns it.

6. undefined vs. null

typeof undefined  // "undefined"
typeof null       // "object"

typeof null is a historical JavaScript quirk. Be explicit about which values an API may return and handle them accordingly.

Organizing Code to Handle Edge Cases

1. Validate at System Boundaries

Treat external input as untrusted. Validate it where it enters the system, then pass values that meet the required contract to the next layer.

2. Use Defensive Access Where It Fits

<?php
    return $user?->profile?->address?->street ?? null; // PHP 8.0+
?>
return user?.profile?.address?.street ?? null;

These expressions handle a nullish value in the chain. They do not replace validation when the application requires those properties to exist.

3. Normalize at a Clear Boundary

Normalize external values once, at a boundary where their meaning is known. This keeps domain code from having to handle several representations of the same value.

4. Separate Responsibilities

  • Controller — HTTP concerns
  • Service — use cases and coordination
  • Domain — business rules and invariants
  • Infrastructure — databases and external APIs

Validate external data at the boundary, enforce domain invariants in domain code, and encode output for its target context. Sanitization and output encoding solve different problems; see the OWASP Input Validation Cheat Sheet and Output Encoding Cheat Sheet.

5. Use Value Objects for Important Invariants

Constructors or factory methods can enforce an invariant so invalid values are harder to pass through core logic. The rule still needs to be enforced on every path that creates or loads the value.

6. Test Boundary Inputs

  • null
  • Empty strings
  • Negative numbers
  • Large numbers
  • Invalid JSON
  • Unexpected encodings
  • Race conditions

7. Make State Checks Explicit

if (user !== null && user !== undefined) {
    // Handle a user value.
}

Choose the check that matches the contract. A test for non-null is not the same as a test that a value is truthy.

Engineering Approach

It helps to distinguish three cases:

  • Invalid input — reject it or return a validation error.
  • Unexpected state — define a recovery path or raise an exception when the caller cannot continue safely.
  • Valid but rare case — handle it explicitly.

Where the design allows it:

  • Make invalid states harder to represent.
  • Normalize input once at a clear boundary.
  • Let domain logic rely only on invariants that are actually enforced.
  • Use type declarations and runtime checks where they clarify the contract.
  • Include boundary conditions in tests.

When those behaviors are defined, edge cases are easier to reason about and stop becoming surprises.


Comments ({{ modelContent.total_comments }})