How to Check if a JSON Object is Empty in PHP
When parsing JSON data in PHP, you often encounter objects that are logically empty. Consider a response like {} or an array containing only null values. If your application relies on the presence of specific properties to proceed with logic, blindly trusting that the object has data can lead to unexpected errors. A common instinct is to check empty() on the decoded array or object, but this approach is unreliable because PHP's empty() function returns true for arrays and objects regardless of their content.
The solution lies in inspecting the actual properties of the decoded structure rather than relying on truthy/falsy evaluation. The most robust method involves checking if the object has any defined keys after decoding.
Using get_object_vars()
One specific approach mentioned in community discussions is using get_object_vars(). This function returns an associative array of the object's properties. If you pass an empty object like {}, the function returns an empty array. You can then check if that resulting array is empty.
Here is how it looks in practice:
$json = '{}';
$data = json_decode($json, true); // Decode to associative array for easier handling
if (empty($data)) {
// Handle the case where the root is null, false, 0, or empty string
} else if (empty(array_keys($data))) {
// The root is an object or array with no keys
}
While this works, wrapping it as empty(get_object_vars($object)) on a decoded object can feel clunky. However, the logic holds: get_object_vars() strips away any magic properties and only returns actual defined attributes. If the result has zero elements, the object is effectively empty from a data perspective.
A cleaner way to achieve the same result without invoking get_object_vars directly on the variable in your mind is to simply count the keys of the decoded array:
$json = '{}';
$data = json_decode($json, true);
if (is_array($data) && empty($data)) {
// Root was null, false, 0, or empty string
} elseif (empty(array_keys($data))) {
// Object or array has no keys
}
Handling Arrays vs. Objects
It is crucial to distinguish between an empty object {} and an empty array []. Both result in zero keys when decoded with the second argument set to true. If you decode with objects (json_decode($json, false)), get_object_vars() becomes necessary to inspect the structure.
$json = '{}';
$data = json_decode($json); // Decoded as stdClass object
if (empty(get_object_vars($data))) {
echo "The object is empty.";
}
If you prefer working with associative arrays, decoding with true allows you to use standard array functions like count() or simply checking if the first key exists using array_key_first():
$json = '{}';
$data = json_decode($json, true);
if (count($data) === 0) {
// Covers both empty arrays and empty objects
}
Performance Considerations
You might worry about the efficiency of calling get_object_vars() or counting keys. For high-throughput applications where you decode millions of JSON payloads per second, function call overhead matters. However, in typical web requests, the cost of inspecting the structure is negligible compared to network latency and database queries.
The main trade-off here is readability versus raw speed. Using count($data) on an array is generally faster than calling get_object_vars() because it avoids allocating a new intermediate array if you are careful with your checks. Yet, get_object_vars() remains the safest semantic choice when working with decoded objects to ensure you are checking defined properties and not magic methods or inherited traits.
Practical Implementation in Laravel
If you are building on top of the Laravel framework, you often receive JSON responses that need validation before processing. Instead of manually decoding and checking emptiness immediately, you can leverage Laravel's validation helpers or cast the data appropriately within your controller logic.
For instance, if you expect a nested structure inside your JSON payload, checking the root level might not be enough. You should ensure that the specific fields required for your business logic are present:
$data = json_decode(request()->getContent(), true);
if (empty($data) && !is_array($data)) {
return response()->json(['message' => 'Invalid payload'], 400);
}
// Proceed with processing only if keys exist
foreach ($data as $key => $value) {
// Process logic
}
This pattern ensures that your application handles empty inputs gracefully without crashing. By explicitly checking for the presence of keys, you avoid undefined errors or null pointer exceptions that occur when trying to access properties on an empty object.