How to loop through PHP object with dynamic keys

How to loop through PHP object with dynamic keys

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

Stefan Bogdanescu

Founder & Senior Architect

How to loop through PHP object with dynamic keys

When parsing a JSON file in PHP, the most common stumbling block occurs when the structure is inconsistent. You might have a dataset where some records contain only a status field, while others include metadata like age, count, or progress. If you attempt to access these fields using static keys—like $data['John']['status']—the script will crash immediately on any record that lacks that specific key.

The error in the initial approach stems from treating associative arrays like indexed lists. In PHP, accessing a non-existent key returns null, but accessing a non-existent array index without checking first causes an "Undefined array key" notice or error depending on your error reporting level. When dealing with dynamic keys where the top-level names (like 'John' or 'Jennifer') are unknown, you must iterate over the available keys rather than hardcoding them.

The standard solution involves using json_decode with the second argument set to true. This converts the JSON string into a native PHP associative array instead of an object. While accessing properties on objects (e.g., $obj->name) is syntactically convenient, it makes iteration over unknown keys significantly harder. You cannot use standard functions like array_keys() or foreach directly on an object instance in older PHP versions, and even in modern versions, iterating by string keys requires explicit casting.

Here is the robust pattern for handling this specific JSON structure:

$string = file_get_contents('/home/michael/test.json');
$json_data = json_decode($string, true); // Decode as associative array

// Iterate over the top-level keys (names)
foreach ($json_data as $name => $record) {
    // Check if 'status' exists before accessing it to prevent notices
    if (isset($record['status'])) {
        echo "Name: {$name}, Status: {$record['status']}\n";
    }

    // If you need to access other dynamic fields, check their existence first
    if (isset($record['age'])) {
        echo "Age: {$record['age']}\n";
    }
    
    // You can also filter out empty values or specific keys if needed
    if ($record['count'] > 0) {
        echo "Count: {$record['count']}\n";
    }
}

By decoding the JSON into an array, $json_data becomes a map where the names are keys and the records are values. The foreach loop automatically handles the iteration over 'John', 'Jennifer', and 'James' without needing to know their names beforehand.

A critical detail here is the use of isset() or the null coalescing operator (??). Since the JSON structure varies, blindly accessing $record['age'] on a simple record like John's will trigger a warning. In production code, you often want to handle missing data gracefully rather than letting PHP emit notices that clutter your logs.

If you are working within the Laravel ecosystem, this pattern aligns well with how models handle polymorphic relationships or dynamic attributes. While you could technically use json_decode($string) without the true argument to keep it as an object, iterating over an object's dynamic properties requires casting it back to an array via (array) $obj. This adds unnecessary complexity for a task that is simpler when starting with an associative array.

For more advanced scenarios where you need to process every key regardless of whether it exists in specific records, you can iterate over the keys of the current record directly:

foreach ($json_data as $name => $record) {
    echo "Processing user: {$name}\n";
    
    // Iterate over all available keys in this specific record
    foreach (array_keys($record) as $key) {
        echo "  Key: {$key}, Value: " . var_export($record[$key], true) . "\n";
    }
}

This nested loop approach is useful when you are debugging the schema or need to log every field available in a record. However, be cautious not to expose sensitive keys unintentionally unless they are explicitly intended for logging. Always validate that the outer array structure matches your expectations before diving into deeper nesting levels.

Our network