PHP Program to Division List with Explanation
PHP
Medium
PHP Error Handling
34 views
1 min read
98 words
This problem helps you practice core PHP fundamentals in a practical way. It builds intuition around line, division, list. Let’s break it down step by step so you can implement it confidently.
Problem Statement
You get n pairs a b. For each, print a/b as integer. If b=0 print ERROR.
Input Format
First n. Next n lines a b.
Output Format
n lines results.
Constraints
n
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
<?php
$inputText=rtrim(stream_get_contents(STDIN));
if($inputText==='') exit;
$inputLines=preg_split('/\\R/', $inputText);
$n=intval(trim($inputLines[0] ?? '0'));
$output=[];
for($i=1;$i<=$n;$i++){
$tokens=preg_split('/\\s+/', trim($inputLines[$i] ?? ''));
$a=intval($tokens[0] ?? 0);
$b=intval($tokens[1] ?? 0);
if($b===0) $output[]='ERROR';
else $output[] = strval(intdiv($a,$b));
}
echo implode(PHP_EOL,$output);
?>
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
You get n pairs a b. For each, print a/b as integer. If b=0 print ERROR.
Input / Output
Input
First n. Next n lines a b.
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
$inputText=rtrim(stream_get_contents(STDIN));
if($inputText==='') exit;
$inputLines=preg_split('/\\R/', $inputText);
$n=intval(trim($inputLines[0] ?? '0'));
$output=[];
for($i=1;$i<=$n;$i++){
$tokens=preg_split('/\\s+/', trim($inputLines[$i] ?? ''));
$a=intval($tokens[0] ?? 0);
$b=intval($tokens[1] ?? 0);
if($b===0) $output[]='ERROR';
else $output[] = strval(intdiv($a,$b));
}
echo implode(PHP_EOL,$output);
?>
Solutions (0)
No solutions submitted yet. Be the first!