PHP count JSON array

PHP count JSON array

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

Stefan Bogdanescu

Founder & Senior Architect

PHP count JSON array

When you pass a JSON string containing an object to json_decode() with the second argument set to true, the result is a native PHP associative array. In your specific case, the top-level structure is an object ({}), not an array. Even though it contains a key named "task" which holds an array of items, calling count() on the decoded top-level variable returns 1.

This happens because count() measures the number of elements in the array itself. Since the decoded JSON represents an object with only one key ("task"), the count is naturally 1. The logic inside that single key is irrelevant to the outer container's size.

To get the total number of task items, you must access the nested array explicitly. You can do this by referencing $task_array['task'] before passing it to count():

$json_tasks = $_POST["json_array"];
$decoded = json_decode($json_tasks, true);

if ($decoded && isset($decoded['task'])) {
    $taskCount = count($decoded['task']);
    echo "Total tasks: " . $taskCount; // Outputs 3
} else {
    echo "Invalid JSON or missing 'task' key.";
}

Handling the Decoding Result

A common pitfall in this scenario is assuming that json_decode() always returns an array. The function behaves differently based on whether the root element of the JSON is an object, an array, or a primitive value like a string or number.

If the JSON starts with {, the result is an associative array (object). If it starts with [, the result is a numerically indexed array. When you use the second parameter as true to enable strict typing, PHP creates standard arrays and objects. However, without that flag, the function returns a stdClass object or a native array depending on the input structure.

In your example:

{
  "task": [...]
}

The root is an object. Therefore, $task_array is an associative array with one element (task). The nested content resides inside that key. If you were to count the root level without accessing the key, you are counting keys in the parent object, not the rows in your list.

Validating Input Before Counting

Always validate the decoded JSON before attempting to access specific keys or calculate counts. While json_decode() returns null if the JSON is malformed, it does not throw an exception by default. If you rely on a count value without checking for null first, your script might produce unexpected results or warnings depending on how you handle the null state in downstream logic.

Additionally, ensure that the key "task" actually exists. In some APIs or dynamic payloads, the structure might change, and accessing a missing key could result in an empty array if not handled carefully, or null if accessed directly without checking. Using isset() or the null coalescing operator (??) prevents undefined index notices:

$tasks = $decoded['task'] ?? [];
$count = count($tasks);

This approach ensures that even if the key is missing, you get an empty array with a count of 0, rather than crashing or reporting garbage data.

Why This Matters in API Development

When building APIs or processing webhooks, relying on the structure of incoming JSON without inspecting it can lead to silent logic errors. You might think you are iterating over a list of items, but you are actually iterating over the top-level keys. By understanding that count() operates on the immediate container, you avoid off-by-one errors and misinterpretations of data volume.

If you are using Laravel, the framework provides helper methods to handle JSON payloads more gracefully. For instance, you can use request()->json('task') to safely extract the nested array without needing to manually decode or check for nulls every time. This reduces boilerplate code and minimizes the risk of accessing undefined keys.

use Illuminate\Http\Request;

$count = Request::of($json_tasks)->get('task', []);
$totalTasks = count($count);

Understanding the distinction between object keys and array elements is fundamental when working with JSON in PHP. The fix isn't about changing how you decode the string, but rather recognizing which variable holds the actual collection you intend to measure.

Our network