PHP Program to Postfix with Error Handling with Explanation
PHP
Hard
PHP Error Handling
27 views
1 min read
86 words
This problem helps you practice core PHP fundamentals in a practical way. It builds intuition around error, postfix, token. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Evaluate postfix expression. If it ever divides by zero or lacks operands, print ERROR.
Input Format
One line tokens.
Output Format
Result or ERROR.
Constraints
Token count
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
<?php
$inputText=trim(stream_get_contents(STDIN));
if($inputText==='') exit;
$tok=preg_split('/\\s+/', $inputText);
$st=[];
foreach($tok as $t){
if($t==='') continue;
if($t==='+'||$t==='-'||$t==='*'||$t==='/'){
if(count($st)<2){ echo 'ERROR'; exit; }
$b=array_pop($st);
$a=array_pop($st);
if($t==='/' && $b===0){ echo 'ERROR'; exit; }
if($t==='+') $st[]=$a+$b;
elseif($t==='-') $st[]=$a-$b;
elseif($t==='*') $st[]=$a*$b;
else $st[]=intdiv($a,$b);
}else{
if(!preg_match('/^[+-]?[0-9]+$/',$t)){ echo 'ERROR'; exit; }
$st[] = intval($t);
}
}
if(count($st)!==1) echo 'ERROR';
else echo strval($st[0]);
?>
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
Evaluate postfix expression. If it ever divides by zero or lacks operands, print ERROR.
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=trim(stream_get_contents(STDIN));
if($inputText==='') exit;
$tok=preg_split('/\\s+/', $inputText);
$st=[];
foreach($tok as $t){
if($t==='') continue;
if($t==='+'||$t==='-'||$t==='*'||$t==='/'){
if(count($st)<2){ echo 'ERROR'; exit; }
$b=array_pop($st);
$a=array_pop($st);
if($t==='/' && $b===0){ echo 'ERROR'; exit; }
if($t==='+') $st[]=$a+$b;
elseif($t==='-') $st[]=$a-$b;
elseif($t==='*') $st[]=$a*$b;
else $st[]=intdiv($a,$b);
}else{
if(!preg_match('/^[+-]?[0-9]+$/',$t)){ echo 'ERROR'; exit; }
$st[] = intval($t);
}
}
if(count($st)!==1) echo 'ERROR';
else echo strval($st[0]);
?>
Solutions (0)
No solutions submitted yet. Be the first!