PHP Code
<?php function calculateTotal($items,$taxRate=0.08){ $subtotal=0; foreach($items as $item){ if($item['quantity']>0){ $lineTotal=$item['price']*$item['quantity']; $subtotal+=$lineTotal; }else{ throw new \InvalidArgumentException("Quantity must be positive"); } } $tax=$subtotal*$taxRate; $total=$subtotal+$tax; return ['subtotal'=>$subtotal,'tax'=>$tax,'total'=>$total]; } class ShoppingCart{ private array $items=[]; public function addItem(string $name,float $price,int $qty=1):void{ $this->items[]=['name'=>$name,'price'=>$price,'quantity'=>$qty]; } public function getTotal():array{ return calculateTotal($this->items); } } ?>
Format
Reset
Copy
Settings
Settings
Indentation Style
Spaces
Tabs
Indent Size
2
4
8
Brace Style
Same line (K&R)
Next line (Allman)
Space after commas
Space around operators
Trim trailing whitespace
Maximum consecutive blank lines
1
2
3
Formatted PHP