MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

PHP Program to Bank Account with Explanation

PHP Easy PHP OOP Basics 33 views
This problem helps you practice core PHP fundamentals in a practical way. It builds intuition around withdraw, deposit, balance. Let’s break it down step by step so you can implement it confidently.
Back to Questions

Problem Statement

Create BankAccount with deposit/withdraw. Withdraw that goes below 0 is ignored. Print final balance.

Input Format

First line q. Next q lines: DEPOSIT x or WITHDRAW x.

Output Format

One integer balance.

Constraints

q

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
<?php class BankAccount{ private $bal=0; function deposit($x){ $this->bal += $x; } function withdraw($x){ if($this->bal >= $x) $this->bal -= $x; } function balance(){ return $this->bal; } } $inputLines=preg_split('/\\R/', rtrim(stream_get_contents(STDIN))); if(!$inputLines || trim($inputLines[0])==='') exit; $q=intval($inputLines[0]); $acc=new BankAccount(); for($i=1;$i<=$q;$i++){ $tokens=preg_split('/\\s+/', trim($inputLines[$i] ?? ''), 2); $cmd=$tokens[0] ?? ''; $x=intval($tokens[1] ?? 0); if($cmd==='DEPOSIT') $acc->deposit($x); elseif($cmd==='WITHDRAW') $acc->withdraw($x); } echo $acc->balance(); ?>

Output Example

Input:
4 DEPOSIT 100 WITHDRAW 30 WITHDRAW 100 DEPOSIT 10
Output:
80

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