stdClass object and foreach loops

stdClass object and foreach loops

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

Stefan Bogdanescu

Founder & Senior Architect

Navigating stdClass Arrays in PHP SOAP Responses

When interacting with legacy web services via SoapClient, you will frequently encounter responses wrapped in nested stdClass objects. The structure is often rigid and generated directly from WSDL definitions, leaving little room for flexibility compared to modern REST APIs returning associative arrays or JSON. In the scenario where a SOAP call returns multiple items within a collection, accessing data requires navigating this specific object graph rather than treating it as a simple array index.

Consider a response where the top-level result contains a property named SMSIncomingMessage. If this property holds an array of stdClass objects, each representing a message, direct array access like $result->GetIncomingMessagesResult[0] will fail. PHP treats these nested structures strictly as objects. To iterate over them, you must explicitly cast the collection to an array or use specific object iteration methods.

Casting Objects to Arrays

The most robust way to handle a stdClass property that contains an array of objects is to cast it using (array). This forces PHP to treat the internal array structure of the stdClass as a standard indexed array, allowing you to leverage foreach loops effectively.

$result = $client->GetIncomingMessages($parameters);

// Safely access the collection and cast it to an array
$messages = (array) $result->GetIncomingMessagesResult->SMSIncomingMessage;

// Now you can iterate cleanly
foreach ($messages as $message) {
    // Access properties like OutgoingMessageID or MessageNumber
    echo "Reference: {$message->Reference}\n";
    echo "Phone Number: {$message->PhoneNumber}\n";
}

This approach works regardless of whether the SOAP response returns zero, one, or many items. If the SMSIncomingMessage property exists but is empty, casting it to an array results in an empty array [], preventing errors during iteration. This pattern is essential when dealing with dynamic data counts from external services where you cannot guarantee a fixed number of return values.

Handling Single vs. Multiple Results

A common pitfall occurs when the SOAP response structure changes based on the payload. If only one message is returned, the property might be a single stdClass object rather than an array. Attempting to cast a single object to an array in PHP returns an associative array containing the object as the key (usually '0' or the class name depending on context), but relying solely on (array) can sometimes be ambiguous if the internal structure isn't strictly indexed numerically.

To ensure compatibility, check the type of the collection before iterating:

$collection = $result->GetIncomingMessagesResult->SMSIncomingMessage;

if (is_array($collection) || is_object($collection)) {
    // Normalize to array for consistent iteration
    $messages = (array) $collection; 
} else {
    // Handle unexpected null or other types gracefully
    $messages = [];
}

foreach ($messages as $message) {
    // Process each item
}

Type Safety and Refactoring

While working with stdClass is unavoidable when using raw SOAP clients, relying on dynamic properties like $message->Reference can lead to runtime errors if the WSDL version changes or if a specific message lacks that field. Modern PHP development often suggests type hinting or DTO (Data Transfer Object) patterns to mitigate this.

In frameworks like Laravel, you might wrap these raw results in a model or a dedicated class to enforce strict typing:

class Message {
    public string $Reference;
    
    public function __construct($stdClassMessage) {
        if ($stdClassMessage) {
            $this->Reference = $stdClassMessage->Reference ?? '';
        } else {
            throw new InvalidArgumentException('Missing Reference');
        }
    }
}

// Map raw objects to typed instances
$mappedMessages = array_map(function($item) {
    return new Message($item);
}, (array) $result->GetIncomingMessagesResult->SMSIncomingMessage);

foreach ($mappedMessages as $msg) {
    // Type-safe access here
    echo $msg->Reference; 
}

This refactoring adds a layer of abstraction that makes your code resilient to changes in the external SOAP service. It also allows you to use Laravel's Eloquent or similar ORM features if you decide to persist this data later, bridging the gap between rigid SOAP contracts and flexible application logic.

Our network