Skip to content
Exercise · Errors and exceptions · lesson 8 of 8

Exercise: out of stock

The stock is kept in an array: the key is an item's name, the value is how many are left, for example ['tea' => 3, 'milk' => 2]. Write a function function take(array $stock, string $name, int $qty): array that takes $qty pieces of the item $name off the stock and returns the stock after that.

If there is not enough of the item, the function throws OutOfStockException with a message like tea: need 5, have 3, which gives the item's name, how many were asked for and how many there are. An item missing from the array counts as an item with 0 left. The OutOfStockException class is already declared in the stub.

  • take(['tea' => 3, 'milk' => 2], 'tea', 2) → ['tea' => 1, 'milk' => 2]
  • take(['tea' => 3], 'tea', 5) → throws OutOfStockException with the message tea: need 5, have 3
  • take(['tea' => 3], 'coffee', 1) → throws OutOfStockException with the message coffee: need 1, have 0

Constraints: $qty is an integer from 1 to 1000; an item with 0 left stays in the array; the other items and their order do not change.

Do not add extra require or use lines unless the task says so explicitly.

stock.php — php
php · 9 lines
Ctrl+Enter run · Esc leave editor