PHP Program to JSON Required Keys with Explanation
PHP
Hard
PHP Error Handling
31 views
1 min read
84 words
This problem helps you practice core PHP fundamentals in a practical way. It builds intuition around json, keys, one. Let’s break it down step by step so you can implement it confidently.
Problem Statement
JSON object must contain keys id and name. Print OK, MISSING_KEYS, or INVALID_JSON.
Input Format
One line json.
Output Format
One word status.
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;
}
if(!array_key_exists('id',$obj) || !array_key_exists('name',$obj)) echo 'MISSING_KEYS';
else echo 'OK';
?>
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).
Solution Guide
Problem
JSON object must contain keys id and name. Print OK, MISSING_KEYS, or INVALID_JSON.
Details
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).
Official Solution
<?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;
}
if(!array_key_exists('id',$obj) || !array_key_exists('name',$obj)) echo 'MISSING_KEYS';
else echo 'OK';
?>
Solutions (0)
No solutions submitted yet. Be the first!