json - PHP json_decode function returns a countable error

$info = json_decode(file_get_contents("php://input"));
if (count($info) > 0)

My website project has the line of code above. When this loads a JSON file, the following error is produced:

count(): parameter must be an array or an object that implements countable in




The functionjson_decode() requires one argument, but it has three additional optional arguments.

The second one is whether or not to return an array. Since the JSON object does not support the countable interface. So to usecount(), you must request an array.

Here is an example:

$info = json_decode(file_get_contents("badjson.jq"), true);
if ($info === null) {
  echo "error\n";
if (count($info) > 0) {
  echo "count: " . count($info) . "\n";

If you pass it bad data, you will have this output:


This code checks forjson_decode() failing to parse the input and exits with a generic error.

Using correctly formatted JSON here:

    "first": {
        "title": "example"
    "second": {
        "title": "example2"

You get presented with the count:

count: 2

For additional information, look up the .

Credit Jigar Shah in comments for pointing out the importance of the second argument being true.

People are also looking for solutions to the problem: php - Explode and transpose nominated comma-separated strings of an associative array


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.