json - PHP json_decode function returns a countable error
897
$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
Answer
Solution:
The function
json_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 use
count()
, you must request an array.Here is an example:
If you pass it bad data, you will have this output:
This code checks for
json_decode()
failing to parse the input and exits with a generic error.Using correctly formatted JSON here:
You get presented with the count:
For additional information, look up the
.
Credit Jigar Shah in comments for pointing out the importance of the second argument being true.