Retrieving Array Keys from JSON Input
When you decode a JSON string in PHP, the resulting data structure depends entirely on how that JSON was formatted. In the specific case provided, where the input contains an entries array of objects, decoding it yields a nested associative array. To access the keys (id, name, age) belonging to the items inside entries, you must first navigate into that sub-array.
The standard approach involves iterating over the outer entries collection and then extracting the keys from each inner item. However, the method you choose depends on whether you need to process every single record or if you simply want to list the unique field names available across all records.
Iterating with JsonDecode and array_keys
The most direct way to achieve this is to decode the JSON string into a PHP variable and then loop through the entries index. Once inside the loop, you can call array_keys() on the current item. This function returns an array of keys for the given array.
Here is a practical implementation:
$json = '{
"entries":[
{"id": "29","name":"John", "age":"36"},
{"id": "30","name":"Jack", "age":"23"}
]
}';
$data = json_decode($json, true);
// Navigate to the entries array
$entries = $data['entries'];
foreach ($entries as $entry) {
$keys = array_keys($entry);
// Outputting keys for the current item
echo implode(', ', $keys) . PHP_EOL;
}
In this example, json_decode is called with the second argument set to true. This flag converts objects into associative arrays, which is generally preferred when working with dynamic key access or iterating over fields. If you omit this flag, $entry would be a stdClass object, and you would need to use functions like get_object_vars() instead of array_keys().
The loop processes each record individually. Because the sample data shows identical structures for every entry, the output will repeat the same list of keys for each iteration: id, name, age. If your dataset were dynamicâcontaining some records with an extra field like email and others withoutâyou could collect all unique keys by merging the arrays returned by array_keys() across the loop.
Handling Empty or Missing Data
A common pitfall when working with JSON input is assuming that every index in the entries array exists or that they share the exact same schema. If a record is missing, json_decode returns null, and accessing $data['entries'] might throw an undefined index error if the key doesn't exist at all.
To make this robust, you should always verify that the decoded variable is not null before attempting to access sub-keys. Additionally, checking if the entries array itself is populated prevents errors on empty JSON responses.
if ($data && isset($data['entries']) && !empty($data['entries'])) {
foreach ($data['entries'] as $entry) {
// Proceed only if the entry is a valid array (or object converted to array)
if (is_array($entry)) {
echo implode(', ', array_keys($entry)) . PHP_EOL;
}
}
}
Using Laravel Collections for Cleaner Syntax
If you are working within a Laravel application, the situation changes slightly regarding syntax and readability. The JsonDecoder class in older versions or raw string handling is often replaced by Laravel's collection helpers when dealing with JSON strings. You can use json_decode followed by collect() to transform the decoded data into a collection instance.
This allows you to chain methods like flatMap or simple loops that feel more idiomatic in the framework:
$entries = collect(json_decode($json, true))->when(function ($collection) {
$keys = [];
foreach ($collection as $entry) {
if (is_array($entry)) {
$keys[] = array_keys($entry);
}
}
// Flatten and get unique keys if necessary
return $keys;
});
While this adds a layer of abstraction, it significantly improves readability when manipulating complex JSON structures. It also handles the conversion to arrays implicitly within collection methods if configured correctly, reducing boilerplate code.
Why This Approach Matters
Understanding how array_keys interacts with nested structures is crucial for dynamic form generation, API debugging, or building flexible data processors. The core logic remains consistent: decode, navigate, iterate, and extract. Whether you are writing a standalone script using raw PHP or integrating into a Laravel project, the fundamental behavior of the JSON decoder and array functions dictates how you access those keys.