Check string length in PHP

Check string length in PHP

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Check String Length in PHP: The Trap of Array Objects

You are encountering a classic edge case in PHP where the strlen() function behaves unexpectedly when applied to DOM nodes returned by XPath queries. Your specific scenario involves loading an HTML file into a DOMDocument, importing it as a SimpleXML object, and attempting to validate the length of an element found via an XPath query.

Your code snippet uses $message = $xml->xpath("//div[@class='contest']");. While the var_dump output confirms that $message[0] is indeed a string with 141 characters, your logic check fails whenever you lower the threshold below 141. The root cause lies in how PHP interprets the return type of the xpath() method versus the scalar string you are inspecting.

Understanding XPath Return Types

In PHP, the DOMXPath::query() method (which powers the ->xpath() syntax on SimpleXML) does not always return a single node or a string. It returns an object that implements the Traversable interface. Depending on the query and the underlying DOM state, this object can behave like an array.

When you pass this $message object directly into strlen(), PHP attempts to determine the length of the object itself rather than the content within it. In many versions of PHP, when a traversable object (like one returned by XPath) is passed to strlen(), the function does not iterate over its contents; instead, it calculates the length of the internal representation or treats the object in a way that often results in a consistent, misleading value—frequently returning 0 or a fixed size depending on the PHP version and specific implementation details.

This explains why your conditional logic breaks. When you check strlen($message) < 130, the function is not measuring the 141-character string inside the first element. It is measuring the "length" of the object wrapper. If that internal measurement is consistently 0 or smaller than your arbitrary threshold, the condition evaluates to true, triggering "There Are No Contests." regardless of the actual text length.

The Correct Approach: Accessing the First Node

To fix this issue, you must explicitly access the first element of the collection returned by XPath before measuring its length. Since var_dump shows your data is an indexed array structure (e.g., [0] => string(141)), you need to index into it.

Here is the corrected logic:

libxml_use_internal_errors(TRUE);
$dom = new DOMDocument();
@$dom->loadHTMLFile($source); // Using @ suppresses warnings from malformed HTML
$xml = simplexml_import_dom($dom);
libxml_use_internal_errors(FALSE);

$messageNodes = $xml->xpath("//div[@class='contest']");

// Validate that the query returned at least one result
if (is_array($messageNodes) && count($messageNodes) > 0) {
    // Access the first node and cast it to string or ensure type safety
    $targetString = (string)$messageNodes[0]; 
    
    if (strlen($targetString) < 141) {
        echo "There Are No Contests.";
    } elseif (strlen($targetString) > 142) {
        echo "There is One Active Contest.";
    } else {
        // Handle the edge case where length is exactly between your thresholds
        echo "Length is within expected range.";
    }
} else {
    echo "No contest divs found.";
}

Handling Empty Collections and Type Safety

The primary pitfall in your original code was assuming $message would always be a scalar string. XPath queries often return DOMNodeList objects or arrays of such objects. Even if there is only one match, the variable holds an object collection until you extract the specific node.

Additionally, notice the usage of (string) casting. While strlen() works on strings, passing a DOMElement directly can sometimes yield confusing results depending on PHP's internal type juggling. Casting ensures you are measuring the textual content, not the object instance.

Another critical detail is error handling with libxml_use_internal_errors. Your source material shows loading HTML from a file. If the HTML is malformed (which is common in contest feeders), loadHTMLFile might fail silently or leave the DOM in an inconsistent state. Using the error suppression operator @ on the load function, as shown above, prevents fatal errors that could stop execution entirely, though it is often better to check for warnings explicitly in production environments.

Why This Matters for Validation Logic

When building validation logic based on string length, relying on the raw return value of library functions like XPath without inspecting their specific output types is a fragile pattern. The behavior of strlen() on non-string inputs is not documented as a primary use case and can change subtly across PHP versions or with different DOM implementations.

By explicitly extracting the node using array indexing and casting it to a string, you ensure that strlen() operates exactly as intended: counting bytes in a character sequence. This approach removes ambiguity and ensures your business logic (displaying "One Active Contest" vs "No Contests") reacts accurately to the actual data length, not the internal state of a DOM node list object.

Our network