PHP Program to Bank Account with Explanation
PHP
Easy
PHP OOP Basics
33 views
1 min read
99 words
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.
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
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
Create BankAccount with deposit/withdraw. Withdraw that goes below 0 is ignored. Print final balance.
Input / Output
Input
First line q. Next q lines: DEPOSIT x or WITHDRAW x.
Output
One integer balance.
Examples
Input:
4
DEPOSIT 100
WITHDRAW 30
WITHDRAW 100
DEPOSIT 10
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
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();
?>
Solutions (0)
No solutions submitted yet. Be the first!