MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

PHP Program to JSON Key Count with Explanation

PHP Easy PHP Error Handling 36 views
This problem helps you practice core PHP fundamentals in a practical way. It builds intuition around json, invalid_json, one. Let’s break it down step by step so you can implement it confidently.
Back to Questions

Problem Statement

Given a JSON object. If invalid, print INVALID_JSON. Else print how many keys it has.

Input Format

One line json.

Output Format

One integer or INVALID_JSON.

Constraints

Total length

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
<?php $js=trim(stream_get_contents(STDIN)); if($js==='') exit; $obj=json_decode($js,true); if(json_last_error()!==JSON_ERROR_NONE || !is_array($obj)){ echo 'INVALID_JSON'; exit; } echo count($obj); ?>

Output Example

Input:
{"a":1,"b":2}
Output:
2

Common Mistakes

- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).

Notes & Extra Practice

Solutions (0)

No solutions submitted yet. Be the first!

Prev Next