MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

PHP Program to Postfix with Error Handling with Explanation

PHP Hard PHP Error Handling 29 views
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.
Back to Questions

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]); ?>

Output Example

Input:
6 0 /
Output:
ERROR

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